It is one of the OAuth 2.0 flows responsible for authorisation. This flow is used for communication between web apps (frontend and backend) and involves the following steps:

User Grants Permission

  • The app redirects the user to the OAuth provider (Google, GitHub)
  • The user logs in and grants access
  • Provider sends back a temp authorisation code

Exchange code for an Access Token

  • Your backend sends the auth code to the provider
  • Provider verifies it and returns an access token
  • You app can now make API requests on behalf of the user

Example

In this example, we are building a very basic web app that integrates with Google Drive and uses Google OAuth 2.0.

Redirect the user to Google’s OAuth Server

First, you have to redirect the user to Google’s auth endpoint

const clientId = process.env.CLIENT_ID  
const redireectURI = "http://localhost:3000/oauth/callback"  
const scope = "https://www.googleapis.com/auth/drive.file"  
  
const authUrl = `https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${encodeURIComponent(scope)}`;  
  
window.location.href = authUrl;  

User Logs in and Grants Permission

Once user logs in and grants permission to access files in Google Drive on his behalf, it redirects back to the app using the redirectURI provided in auth url and provides you with a temporary code that needs to be exchanged for auth token. Usually, it will be encoded with Base64.

http://localhost:3000/oauth/callback?code=4/0Af...XYZ  

Exchange the code for an Access Token

Frontend/client needs to send a request to the backend service that can exchange it for an access token and provide it to the frontend. For this to work, you will need the following:

  • clientid
  • clientSecret
  • code
  • grantType
  • redirect url.
import axios from "axios";  
  
const tokenEndpoint = "https://oauth2.googleapis.com/token";  
  
async function getAccessToken(authCode: string) {  
  const response = await axios.post(tokenEndpoint, {  
    client_id: "YOUR_GOOGLE_CLIENT_ID",  
    client_secret: "YOUR_GOOGLE_CLIENT_SECRET",  
    code: authCode,  
    grant_type: "authorization_code",  
    redirect_uri: "http://localhost:3000/oauth/callback",  
  });  
  
  return response.data.access_token;  
}  
  

Common Pitfalls

Tokens expire quickly

The biggest problem with tokens is that they expire quickly (up to an hour). To prevent sign outs and sign ins, you can use a Refresh token to keep user logged in and server can reauthenticate on your behalf.

Don’t store access tokens in Local Storage

You should never store access tokens in a local storage because they can be easily accessed programatically by Cross Site Scripting.

CORS Issues

Because there are CORS restrictions, you cannot really call OAuth endpoints directly from your browser. For that, you always have to use a backend proxy.