Get Userinfo from Oauth2 Google Contacts API

自闭症网瘾萝莉.ら 提交于 2019-11-29 10:27:29

I'm guessing credential.getRequestInitializer() is null.

I've solved this by setting an custom request initializer to the credential object like this

GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(this.TRANSPORT).setJsonFactory(this.JSON_FACTORY)
.setClientSecrets(Constants.CLIENT_ID, Constants.CLIENT_SECRET).setRequestInitializer((new HttpRequestInitializer(){
                @Override
                public void initialize(HttpRequest request)
                        throws IOException {
                    request.getHeaders().put("Authorization", "Bearer " + accessToken);
                }
            })).build()

Google's documentation especifies the following:

** For example, a call to the UserInfo API using the access_token query string parameter looks like the following:

GET https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken} A call to the same API using the access token in the HTTP header looks like the following:

GET /oauth2/v1/userinfo HTTP/1.1 Authorization: Bearer {accessToken} Host: googleapis.com**

Hope this will help you

If you obtained already the access token (GoogleTokenResponse), then you can also do this:

HttpTransport transport = new NetHttpTransport();

List<String> applicationScopes = Arrays.asList(
  PlusScopes.USERINFO_EMAIL,
  PlusScopes.USERINFO_PROFILE
);

GoogleAuthorizationCodeFlow flow
  = new GoogleAuthorizationCodeFlow.Builder(
    transport,
    JacksonFactory.getDefaultInstance(),
    "your-client-id.apps.googleusercontent.com",
    "your-client-secret",
    applicationScopes).build();

String userId = googleTokenResponse.parseIdToken().getPayload().getSubject();
Credential credential = flow.createAndStoreCredential(googleTokenResponse, userId);
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);

GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/userinfo");
HttpRequest request = requestFactory.buildGetRequest(url);
String userIdentity = request.execute().parseAsString();

The userIdentity would then look like this:

{
  "id": "105358994046791627189",
  "name": "Benny Neugebauer",
  "given_name": "Benny",
  "family_name": "Neugebauer",
  "link": "https://plus.google.com/+BennyNeugebauer",
  "picture": "https://lh4.googleusercontent.com/-dtvDIXCEtFc/AAAAAAAAAAI/AAAAAAAAAoE/1CKd3nH9rRo/photo.jpg",
  "gender": "male",
  "locale": "de"
}

If you want you can parse the userIdentity into your own class using Jackson:

ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.readValue(userIdentity, YourUser.class);

Here are the dependencies that I used for this example:

<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-plus</artifactId>
  <version>v1-rev401-1.22.0</version>
</dependency>

<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.13</version>
  <type>jar</type>
</dependency>

In order to retrieve data from the Userinfo API you have to request access to its OAuth scope:

https://www.googleapis.com/auth/userinfo.profile

Also add the scope https://www.googleapis.com/auth/userinfo.email if you want to retrieve the email address.

In your code I don't see where you set the OAuth scopes you are requesting access to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!