【问题标题】:How to get userinfo with google-api after succesfully been authenticated?成功通过身份验证后如何使用 google-api 获取用户信息?
【发布时间】:2013-05-23 12:59:57
【问题描述】:

我在使用 gmail 帐户成功验证后尝试获取用户信息(tok 是有效令牌):

        GoogleCredential credential2 = new GoogleCredential.Builder()
                .setTransport(TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
                .setRequestInitializer((new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest request)
                            throws IOException {
                        request.getHeaders().setAuthorization("Bearer ".concat(tok));
                    }
                }))
                .build();

        Oauth2 userInfoService = new Oauth2.Builder(TRANSPORT,
                JSON_FACTORY, credential2.getRequestInitializer())
                .setApplicationName(APPLICATION_NAME).build();

        Userinfo userInfo = userInfoService.userinfo().get().execute();
        logger.warn("User email: {}", userInfo.getEmail());
        logger.warn("User gender: {}", userInfo.getGender());
        logger.warn("User complet name: {} - {}", userInfo.getFamilyName(), userInfo.getName());

但日志显示所有字段为'null',返回的json数据只包含id:

{
 "id": "113695880661351193041"
}

我应该做什么?添加一个特殊的范围来做到这一点?我试了几次都没有成功,只是添加了scope=https://www.googleapis.com/auth/userinfo.profile作为url参数,也许是错的?

希望有人可以帮助或知道如何为我的请求添加范围并从该服务获得正确的响应。

【问题讨论】:

    标签: java google-api-java-client userinfo


    【解决方案1】:

    这对我有用:

    Credential credential = OAuth2Utils.newFlow().loadCredential(userId);
    
    Oauth2 service = new Oauth2.Builder(OAuth2Utils.HTTP_TRANSPORT, OAuth2Utils.JSON_FACTORY, credential).setApplicationName("appname").build();
    
    UserInfo userInfo = service.userinfo().get().execute();
    

    这些是返回的一些属性:

    • userInfo.getBirthday()

    • userInfo.getFamilyName()

    • userInfo.getGender()

    • userInfo.getGivenName()

    • userInfo.getHd()

    • userInfo.getLink()

    代码中提到的实用类OAuth2Utils

    /** Global instance of the HTTP transport. */
    public final static HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();
    
    /** Global instance of the JSON factory. */
    public final static com.google.api.client.json.JsonFactory JSON_FACTORY = new com.google.api.client.json.jackson2.JacksonFactory();
    
    public static GoogleAuthorizationCodeFlow newFlow() throws IOException {
        return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientCredential(),
                Arrays.asList(SCOPES)).setCredentialStore(new OAuth2CredentialStore()).setAccessType("offline")
                .setApprovalPrompt("force").build();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 1970-01-01
      • 2020-02-28
      • 2019-11-08
      • 1970-01-01
      • 2019-08-31
      • 2018-09-03
      • 2011-10-31
      • 2011-10-06
      相关资源
      最近更新 更多