首页 文章

如何从java代码验证google oauth2令牌

提问于
浏览
0

我有一个Android应用程序和Web服务器一起工作 . 现在我希望用户通过谷歌从Android应用程序登录(或使用Android上的一个谷歌帐户) . 然后andriod应用程序通过服务调用将令牌传递给我的网络服务器......在这里我无法实现如何从具有该令牌的谷歌获取用户电子邮件或 Profiles 数据 .

我可以在浏览器中拨打这样的电话:https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=

但是如何使用谷歌图书馆呢?使用什么库等等?

2 回答

  • 1

    根据您尝试使用的服务,只需选择Google's Client Libraries中的正确服务,然后查看Google+ Sample .

    对于所有API,上半部分应该基本相同 . 要获取用户信息,您需要oauth2 library,然后执行此类操作(取自this example):

    // Set up the HTTP transport and JSON factory
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    
    // Set up OAuth 2.0 access of protected resources
    // using the refresh and access tokens, automatically
    // refreshing the access token when it expires
    GoogleAccessProtectedResource requestInitializer =
        new GoogleAccessProtectedResource(accessToken, httpTransport,
        jsonFactory, clientId, clientSecret, refreshToken);
    
    // set up global Oauth2 instance
    Oauth2 oauth2 = new Oauth2.Builder(httpTransport, jsonFactory, requestInitializer)
        .setApplicationName("Google-OAuth2Sample/1.0").build();
    
    Userinfo userinfo = oauth2.userinfo().get().execute();
    
  • 1

    我使用了这里的代码示例:https://github.com/googleplus/gplus-verifytoken-java,它似乎更新 . 代码最终是这样的:

    GoogleCredential credential = new GoogleCredential().setAccessToken( accessToken );
    Oauth2 oauth2 = new Oauth2.Builder(
        UrlFetchTransport.getDefaultInstance(),
        JacksonFactory.getDefaultInstance(), credential )
        .build();
    Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken( accessToken ).execute();
    
    // ... check tokeninfo expiry and issued to etc ...
    

相关问题