Brief Introduction To Refresh and Access Tokens:

Insights shared by Bhojraj Shrestha

Edit this text

Introduction

Definition of Tokens in Authentication:-

Tokens are basically random string generated from some libraries like JWT ( Json-Web-Token ) to make it complex and secured so that it can be used in very confidential work such as verifying login , logout and more . There are generally two kinds of token used in the verifying the users and their login sessions. They are Refresh and Access Tokens. Broadly, the token are similar and the process of generating them are also same but the main difference of the two token is refresh token is long lived and access Tokens are short lived.

// you can also check the official website for more info : Click Here

This is how it looks like. Actually it has two parts header and payload where you can insert your data and it will encode the data to this large complex and secure string to make more secured you can tick the secret which is professionally preferred.

Setting Up:

You can install jwt in your code and use it to generate tokens .

npm i jsonwebtoken

Importance of Token-based Authentication:

Ii is very important part of authenticating users because It has high security since it is encoded in a large complex string and also can only be decoded by the server only with the secret key.

Concept of using tokens in LOGIN:

Token are basically used for authenticating purposes and creating login sessions. Let’s discuss the scenario of why and how it is used in login. Earlier, Only access token was used to be created while you login which provides you login session(session is period where you are logged in and can access the data) . Access token is very short lived (may be 10 minute or 1 hour or 1 day). It might be variable but it is generally very short lived so the problem here is every time the token expires. The user needs to login again which is very important as well to make it more secure. but logging every time you use it is very problematic and seem unreliable so the concept of refresh token and access token comes in use. so now how does it work together is the refresh token is long lived (may be for a month or months or even year)token and stored in both in the database and user so whenever the access token get expired the frontend will hit an endpoint to request to verify the user and create a new session all by itself until the refresh token get expired. It is basically the concept of refreshing the access token by itself so that user don’t have to login every time . this is why refresh and access token is used in login.

so Now let’s talk about how it is used , As the user login, the refresh token and access token are generated using the jwt library: This is how it is generated.

import jwt from "jsonwebtoken"
//It is made as a methods to userschema so that you can get the data of the user and generate token
// from the data since it hold data of the user itself it can also use to get user information 
// by decoding using "jwt.verify" method.(for authentication purpose)
userSchema.methods.generateAccessToken = () => {
   return jwt.sign(
    {
        id: this._id,
        username: this.username,                  // User information from the user model or database
        email: this.email
    },
    process.env.ACCESS_TOKEN_SECRET,       // it can be any string it is important because wothout 
                                          //Access_Token_secret the token can't be verified and decode
    {
        expiresIn:process.env.ACCESS_TOKEN_SECRET_EXPIRY  //it is the time for expiry we set it's like
                                                           // 1d
    })
}

same for the refresh token as well .

import jwt from "jsonwebtoken"
userSchema.methods.generateAccessToken = () => {
   return jwt.sign(
    {                                           // User information from the user model usually 
                                                  // id:this._id is only required
        id: this._id,

    },
    process.env.ACCESS_TOKEN_SECRET,       // it can be any string it is important because wothout 
                                          //Access_Token_secret the token can't be vrified and decode
    {
        expiresIn:process.env.ACCESS_TOKEN_SECRET_EXPIRY  // it is the time for expiry we set it like
                                                           // 10d
    })
}

After it is generated we save the refresh token in database base and send the response to the user with refresh token and access token in the cookies.

return res
  .status(200)
  .cookie("accessToken",accessToken, options)
  .cookie("refreshToken",refreshToken, options)
  .json(
    new apiResponse(
      200,
      {
        user:userLoggedIn                       //info of the user 
      }
    )

Now, when the user access token expires we hit an endpoint in the frontend and make controller to refresh the access token by verifying the user .

// "controller" to refresh the access token when the endpoint is hitted. 
// [Note endpoints are set in the router and the refreshSession method is executed when the endpoint 
// is hitted in the fronted]

const refreshSessions = async (req,res) => {

      try {
        const incomingRefreshToken = req.cookie?.refreshToken ||
        req.body?.refreshToken

        if(!incomingRefreshToken){
          throw new apiError(400,"refreshToken is not found")
        }


      const decodedToken = jwt.verify(incomingRefreshToken,
        process.env.REFRESH_TOKEN_SECRET)

        if(!decodedToken){
          throw new apiError(400,"refreshToken invalid or expired.")
        }
      const user =  User.findById(decodedToken?._id)

      if(!user){
        throw new apiError(400,"User doesnot found .")
      }
      if(incomingRefreshToken !== user?.refreshToken){
        throw new apiError(400, "RefreshToken doesnot matched")
      }
      const {refreshToken, accessToken} = await generateAccessAndRefreshToken(user._id)

      const options = {
        httpOnly: true,
        secure: true
      }

      res
      .status(200)
      .cookie("accessToken", accessToken, options)
      .cookie("refreshToken", refreshToken, options)
      .json(
        new apiResponse(
          200,
          {
            refreshToken,accessToken
          },
          "accesstoken refreshed successfully."
        )
           )
          } 
     catch (error) {
        throw new apiError(401,error?.message || "Invalid refreshToken")
      }

  }

This is how it is used in the login not only in login but It can also be used in logout and authenticating user.

you can learn and understand more and better in depth from the tutor hitesh choudhary and especially from backend course .