如何获取当前已验证用户的个人资料信息?

时间:2021-01-20 10:20:36

标签: java google-oauth

我正在尝试使用从 Android 应用程序获得的访问令牌从 google userinfo 端点获取用户信息。我收到以下消息:

GET https://www.googleapis.com/oauth2/v1/userinfo?oauth_token=string
{
  "code" : 401,
  "errors" : [ {
    "domain" : "global",
    "message" : "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "reason" : "unauthorized"
  } ],
  "message" : "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
  "status" : "UNAUTHENTICATED"
}

现在,我通过邮递员以这种方式获取访问令牌: enter image description here

您可以看到范围是正确的。在我在下一步中提供我的电子邮件地址和密码后,令牌会自行生成。在代码中,我以这种方式使用它。我做错了什么?

public Optional<SocialProfileDto> findByToken(String token) {
        Credential credential =
                new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(token);
        
        Oauth2 oauth2 = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName(
                  "Oauth2").build();
        Userinfoplus userinfo = null;
        
        try {
            userinfo = oauth2.userinfo().get().setOauthToken(token).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
         try {
            userinfo.toPrettyString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

0 个答案:

没有答案
相关问题