Google OAuth2 Validate access token in Server Flow

2.1k views Asked by At

I'm manually writing OAuth2 Server Flow to allow users to login using Google (and other websites, but let's focus on Google).

I have the basic flow working:

  1. user clicks on the login link.
  2. goes to Google and sees consent screen.
  3. accepts.
  4. redirected back to my website.
  5. server takes relevant information and logs user in.

So far so good. Now I want to make sure that the server remembers the user for next time. For that I store the token along with other user data on the server.

Now, how do I check, server-to-server, if the token is still valid? I have it's expiration time, so I know it's invalid after that time passes, but what do I do then? Should I ask for a permanent (offline) token if I only want to allow login?

1

There are 1 answers

2
dvsakgec On BEST ANSWER

As a result of authorization success from Google, you should also get refresh_token. If you are not getting then do the following.

  1. when you are redirecting to Authorization endpoint add additional parameter access_type=offline which will make sure that you will get refresh_token
  2. Use refresh token to get additional access tokens.

Now, for validating you can hit the token validation endpoint of Google, if you are not maintaining the state. If you are maintaining the state then you can validate the expiry of token if token is only signed, if encrypted then you have to validate from Google.

You can play with different Google OAuth URLs here

more details on token validation here