Access and Refresh Tokens

KaranKaran
2 min read

Introduction :

Both access and refresh tokens are types of authorization/authentication tokens.

Access tokens are used to authorize users to access a restricted or protected resource.

Whereas, refresh tokens are used to obtain or re-generate new access tokens so that users don’t have to re-login again to keep using the protected services on a website. Off course, there are more distinguishable factors so let’s look at them.

Access token :

  • It’s short lived. Meaning that like for example 15 mins or 5 hours (can vary as per requirement, but it’s short lived) So once this expiration time is finished, that access token gets expired and then user is no longer having the access to the protected resources on a website.

  • We can create an access token with jsonwebtoken package. (A popular package for generating jsonwebtokens).

  • Usually stored in memory (like local variables) to minimize XSS attacks.

Let’s see some code:

The code below is a function responsible for generating an access token. Here we’re using two secured variables from the .env file.

1) ACCESS_TOKEN_SECRET (any hard/difficult string acting as a secret/password)
2) ACESS_TOKEN_EXPIRY (an expiry number like 15m, 20m (m = minutes) etc)

function () {
  return jwt.sign(
    {
      _id: this._id,
    },
    process.env.ACCESS_TOKEN_SECRET,
    {
      expiresIn: process.env.ACCESS_TOKEN_EXPIRY,
    }
  );
};

Refresh token :

  • It’s long lived. Meaning it can live up to longer time than the access token. For example, 2 days, 10 days etc. When access token is expired, so we can use this refresh token to generate a new access token ( in this process a new refresh token is also generated)

  • We can use the same package (jsonwebtoken) to generating a refresh token.

  • We can store it in database but in an encrypted form or they are also stored in an HTTP-only cookie (safe cookie in simple terms, away from attacks).

Let’s see some code here as well?

The code below is a function responsible for generating an refresh token. Here we’re using two secured variables from the .env file.

1) REFRESH_TOKEN_SECRET (any hard/difficult string acting as a secret/password)
2) REFRESH_TOKEN_EXPIRY (an expiry number like 10d, 15d (d = days) etc)

function () {
  return jwt.sign(
    {
      _id: this._id,
    },
    process.env.REFRESH_TOKEN_SECRET,
    {
      expiresIn: process.env.REFRESH_TOKEN_EXPIRY,
    }
  );
};
0
Subscribe to my newsletter

Read articles from Karan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Karan
Karan