Use authorized Google Cloud endpoints with Google Login

I have an application that uses Google Cloud endpoints. Some methods require authorization, so I followed this tutorial. This requires GET_ACCOUNTS permissions.

I am updating a runtime permissions application. I do not like to request permission to read contacts, but GET_ACCOUNTS is in the same group. Because of this, I am looking to use authorization without GET_ACCOUNTS permission.

I think Google Sign In may work, but I can’t find a way to use the result from Google login.

This is the code used to create the object to make calls to the endpoint:

Helloworld.Builder helloWorld = new Helloworld.Builder(AppConstants.HTTP_TRANSPORT, AppConstants.JSON_FACTORY,credential); 

The credential object must be an HttpRequestInitializer , but from Google Sign In I get a GoogleSignInAccount .

So can this be done? How to do it?

+5
source share
1 answer

I finally found a solution. Use of the tutorial found here .

You must add the client ID in GoogleSignInOptions:

  GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(CLIENT_ID) .requestEmail() .build(); 

Following the tutorial, you will finally get a GoogleSignInAccount. Set the token from the GoogleSignInAccount in the GoogleCredential object:

 GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()) .setJsonFactory(JacksonFactory.getDefaultInstance()) .build(); credential.setAccessToken(GoogleSignInAccount.getIdToken()); 

These credentials are ready to make authenticated calls to Google Cloud Enpoints.

Note that you must remove the "server: client_id:" part from the identifier CLIENT_ID. Therefore, if you used this:

 credential = GoogleAccountCredential.usingAudience(this, "server:client_id:1-web-app.apps.googleusercontent.com"); 

Your CLIENT_ID will be:

 CLIENT_ID = "1-web-app.apps.googleusercontent.com" 

Also note that the token is valid for a limited period of time (Aprox. 1 hour in my testing)

+6
source

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


All Articles