简体   繁体   中英

Google Login - 401 error “Login Required” when trying to access userinfo

I have an Android app that supports Login with Google using PlusClient . After I connect, I get the auth token using an AsyncTask and the GoogleAuthUtil.getToken method as follows:

private void fetchAuthToken() { AsyncTask task = new AsyncTask() {

        @Override
        protected String doInBackground(Void... params) {
            String token = null;
            String scope = "oauth2: https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email";//"oauth2: "+ Scopes.PLUS_PROFILE;
            Bundle appActivities = new Bundle();
            appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES, visiblaeActivities);
            try {                   
                token = GoogleAuthUtil.getToken(Login.instance.context, mPlusClient.getAccountName(), scope, appActivities);
            } catch (UserRecoverableAuthException e) {                  
                loginActivity.startActivityForResult(e.getIntent(), REQUSET_TOKEN_PERMISSIONS_RESLOVE_ERR);                 
            } catch (IOException e) {
                e.printStackTrace();
            } catch (GoogleAuthException e) {
                e.printStackTrace();
            }
            return token;
        }

This works great, and then I send the token to my backend which is in node.js, there, I try to fetch the user details from google using this request:

https://www.googleapis.com/oauth2/v2/userinfo?access_token=' + access_token

and then I get the user's details and everything is Hunky Dory. The problem is, sometimes I get this error that the token is not valid, which looks like this:

"error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }

And my guess is someone tries to login with google but can't connect for some reason. this is hard to debug because it happens sporadically, and most users login successfully. Anyone?

PS I only fetch the token after the user is connected, ie - I call fetchAuthToken() within the onConnected callback, so the user is definitely logged in by then

My idea: are you keeping your session info? Your http client needs to keep track of the session otherwise the token might become invalid.

BasicCookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

and then add context to your post/get/whatever request you are making

client.execute(post, localContext);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM