Refresh And Access Tokens in Software Backend on a server

Rohit dudiRohit dudi
3 min read

Refresh Token is usually a long duration (days or months) token that is used to provide a new access token to a user after expiring their short duration (some hours or days) Access token.

and refresh token is stored in user database schema to authenticate and authorize the request, and Both refresh token and access tokens are encrypted and store the user ID in itself.

Encryption and decryption of tokens is done by SECRET_ENVIRONMENT_VARIABLES using any secure library with Efficient cryptography algorithms.

while generating the new access token for user after authentication, the refresh token is also regenerated and changed in user database schema and both tokens are returned to user through secure cookies (it can only changed on server side).

Here is a javascript code example to understand how we regenerate the access and refresh token-

Javascript Code example to understand refresh token and access token

const refreshTheAccessToken = asyncHandler(async (req, res) => {
    // extract the refreshToken
    const incomingRefreshToken =
        req.cookies?.refreshToken || req.body.refreshToken;

    // if it is not than it's a bad request
    if (!incomingRefreshToken) {
        throw new ApiError(300, "Unathorized request");
    }

    // decode the refresh token using secure environment variables
    const decodedRefreshToken = jwt.verify(
        incomingRefreshToken,
        process.env.REFRESH_TOKEN_SECRET
    );

    // while genearting the token i have already included the _id of user
    // using id find the user by database query and remove the sensitive data
    const requesterUser = await User.findById(decodedRefreshToken._id)

    // if user not found than obviously refresh token is invalid
    if (!requesterUser) {
        throw new ApiError(400, "invalid refresh token");
    }

    // if the incoming refresh token is matching with existing refresh token of current user in databse than
    if (requesterUser.refreshToken == incomingRefreshToken) {
        // after authentication
        // tryCatch is a good practice for error handling and optional chaining
        try {
            // i have already created a method to generate new tokens
            // cause i also use this method for login Endpoint 
            // passing the _id it will inject the new refresh token in user schema
            const { accessToken, refreshToken } =
                generateAccessAndRefreshTokens(requesterUser._id);

            // options for cookies (server side changable only)
            const options = {
                httpOnly: true,
                secure: true
            };

            // after regenerating the tokens and changing on user schema
            // restore the user in a new variable for updated data while removing the sensitive data
            const loggedInUser = await User.findById(requesterUser._id).select(
                "-password -refreshToken"
            );

            // now return the response by method chaining
            return res
                .status(200)
                .cookie("accessToken", accessToken, options)
                .cookie("refreshToken", refreshToken, options)
                .json(
                    // (i am using) ApiResponse is a utility function that extends the api response class in node.js
                    new ApiResponse(
                        200,
                        {
                            user: loggedInUser,
                            accessToken,
                            refreshToken
                        },
                        "Access token refreshed successfully"
                    )
                );
        } catch (error) {
            // this one is easy peasy as well
            throw new ApiError(400, error.message || "Error generating tokens");
        }
    } else {
        // if not matched
        throw new ApiError(200, "refresh token is expired or used.");
    }
});

remember this is my algorithm to achieve this particular functionality

You can always do it better and optimize efficiently.

thanks for reading this article, i hope this was really easy explained.

I am Rohit keep reading my easy explained articles.

how the refresh and access tokens works?

10
Subscribe to my newsletter

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

Written by

Rohit dudi
Rohit dudi

A Full Stack Engineer