I want to integrate google sign in to my app, when user first sign in I will create an account bind to this, so I need some profiles like gender, locale, etc. and I tried as
I spent some time to find a solution so let me share current way to achieve it.
You need to extend Google Sign in options like this:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.google_client_id)) //like: '9241xyz.apps.googleusercontent.com'
.requestEmail()
.requestProfile()
.requestServerAuthCode(getString(R.string.google_client_id))
.build();
Then in response you receive GoogleSignInResult object with GoogleSignInAccount. You extract both token id and auth code from it.
private void handleGoogleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
String authCode = acct.getServerAuthCode();
String idToken = acct.getIdToken();
}
}
What you need to do next is to get access_token with POST request:
POST https://www.googleapis.com/oauth2/v4/token
Body (x-www-form-urlencoded):
grant_type authorization_code
client_id 9241xyz.apps.googleusercontent.com
client_secret MNw...fMO
redirect_uri ""
code auth_code_from_google_account
id_token id_token_from_google_account
Request can be done in Android app, but I recommend to do it on server side as it's not safe to keep client_secret in Android app. But it's up to you. Response for such request looks like this:
{
"access_token": "ya29.GluIBuHTXZ...kTglmCceBG",
"expires_in": 3552,
"scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.me",
"token_type": "Bearer",
"id_token": "eyJhbGciOiJSUzI1NiIsImt....V6EAlQd3-Y9CQ"
}
Then you can query user profile endpoint for user details:
GET https://www.googleapis.com/oauth2/v3/userinfo
Headers:
Authorization : Bearer ya29.GluIBuHTXZ...kTglmCceBG
Response looks like this:
{
"sub": "107...72",
"name": "Johny Big",
"given_name": "Johny",
"family_name": "Big",
"profile": "https://plus.google.com/107417...990272",
"picture": "https://lh3.googleusercontent.com/-....IxRQ/mo/photo.jpg",
"email": "johny.biggy.test@gmail.com",
"email_verified": true,
"gender" : "male",
"locale": "en"
}
However, if user doesn't have public access to info about him, gender field might be missing here. Probably you need to ask for additional scope in Google Sign in request, but I didn't check. (sharing options are under Google account page: https://myaccount.google.com/personal-info)