Get Userinfo from Oauth2 Google Contacts API

北战南征 提交于 2019-12-18 05:57:13

问题


Error which i am getting:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
  "code" : 401,
  "errors" : [ {
    "domain" : "global",
    "location" : "Authorization",
    "locationType" : "header",
    "message" : "Invalid Credentials",
    "reason" : "authError"
  } ],
  "message" : "Invalid Credentials"
}

Below code, i am using:

GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(this.TRANSPORT).setJsonFactory(this.JSON_FACTORY)
    .setClientSecrets(Constants.CLIENT_ID, Constants.CLIENT_SECRET).build();
credential.setAccessToken(tokenResponse.getAccessToken());
credential.setAccessToken(tokenResponse.getRefreshToken());

Till here, i get Refresh token, Access Token, etc

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

It fails at below line: (Dont know, Why?)

Userinfo userInfo = userInfoService.userinfo().get().execute();

I searched on web, and i get very less examples of it and rare materials. Any body has any idea on it?

What am i doing wrong?


回答1:


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




回答2:


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>



回答3:


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.



来源:https://stackoverflow.com/questions/11602334/get-userinfo-from-oauth2-google-contacts-api

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