Login with Google (Code to Access Token) — Any client to Any server

There are a lot of Login with Google tutorials, posts, videos, libraries on the Internet. But there seem to be almost zero articles about how to get a code from client and send it to the server, where the server fetches the tokens. Especially ones that work.

Luckily this story will cover just that. We will have a JavaScript client with a login to Google that will get a code and it send it to an ExpressJS server where that server will return us the access token back.

Do note that this is just for demo purposes, to show you how it works in code. Whatever you do with it is up to you.

Photo by marcos mayer on Unsplash

Before starting

Client

It’s important to call grantOfflineAccess as that will let Google know that we want the code back, not the profile info.

Once you get the code back, you can submit it to your backend server. Again this is the CODE flow of authentication.

In Google’s authentication code flow it is required for the redirect_uri to be ‘postmessage’ instead of a URI.

Server

The important part is that this is Server side. Client already accepted our app, we already got the code, there is no callback url needed. In simple terms, we have the code, now give us the tokens based on it.

If you have the client and the server on the same domain. Like running a Ruby on Rails app or Express serving client, then yes, callback url is the way to go. But we are not doing that here. In our case the client is separated, we can’t use the callback, as the server would not know which client requested it.

Of course, this can be handled on all on the client. But we want to access users info when the user is not present on the site. In other words and ‘offline’ access.

Thats it. Whole code can be fund here: https://github.com/zprima/js-google-code-to-token

developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store