7

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?

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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> 

Comments

0

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.

1 Comment

I have added that scope as well... and its working fine... After grant access i fail to get required response. So in short, i included email scope as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.