Get Userinfo from Oauth2 Google Contacts API

The error I am getting is:

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 use:

 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()); 

So far I am getting update token, access token, etc.

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

The following line cannot be executed: (Do not know why?)

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

I searched on the Internet and I get very few examples of this and rare materials. Does any body have any idea about this?

What am I doing wrong?

+6
source share
3 answers

I assume credential.getRequestInitializer () is null.

I solved this by setting my own request initializer in a 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 documentation defines the following:

** For example, calling the UserInfo API using the access_token query string parameter looks like this:

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

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

Hope this helps you

+5
source

If you already received an access token ( GoogleTokenResponse ), 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(); 

userIdentity will 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 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> 
+1
source

To retrieve data from the Userinfo API, you must request access to your OAuth scope:

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

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

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

0
source

Source: https://habr.com/ru/post/921078/


All Articles