beachCode
beachCode

Reputation: 3530

Getting a Google OAuth access token from an id_token

I'm using Google authentication with the redirect_uri option (to avoid the pop-up). When the user signs in to Chrome I can get an access token, but in Safari (for example), I can't figure out how to get an access token. The redirect querystring includes an id_token, which I can successfully verify using this endpoint:

https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123

This gives me some info about the user, but what I really want is an access token since my backend API expects it.

Can I get an access token from an id_token? If so, how. I can't find any examples.

Clarification: I'm not trying to authenticate my app, I'm getting the id_token from the user authenticating via Google sign in on the front-end.

Upvotes: 9

Views: 15387

Answers (1)

sg3s
sg3s

Reputation: 9567

Only authenticating users

If you are not using the Google APIs and just using the token for authenticating users you should only verify the id_token and not use an access token. The id_tokens are an OpenID Connect concept used to inform the client (your application) some basic information about the currently logged in user.

To verify an id_token you can use the documentation describing as much or this related question on Stackoverflow.

Using Google APIs on behalf of your users

If you want to use Google APIs in the name of the user however, you will need an access_token as id_tokens are generally not used for authentication with backends. To get an access token the user needs to authorize your app to be able to access Google APIs on their behalf. If you're using the gapi library then the process of doing calls to the Google APIs is likely mostly hidden, but it should have an access token somewhere.

This Google documentation describes what is happening behind the scenes.

https://developers.google.com/identity/protocols/OAuth2

If you want to access Google APIs on behalf of your users on the backend you might have to follow a different process than what your frontend is using. The response type in authorization requests defines which process is used (that is why I asked which response type is used). But the Javascript library behind the gapi npm package seems to support it, though it might not be easily accessible the way you're using it.

https://developers.google.com/api-client-library/javascript/reference/referencedocs#googleusergetauthresponseincludeauthorizationdata

Also checkout the offline options, maybe that is what you're looking for? If this does not help you can still checkout the Oauth2 documentation page I referenced earlier for links to other options / other languages to get auth tokens.

Upvotes: 8

Related Questions