Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Prathviraj H
Prathviraj H

Posted on

Secure Authentication in CampusX Using JWT

Introduction

Authentication is a critical part of any web application. In CampusX, we useJWT (JSON Web Tokens) to handle user authentication efficiently and securely. JWT provides a stateless way to verify users while minimizing database queries.

This blog explains:

  • What JWT is and why it's important.
  • How CampusX uses access and refresh tokens.
  • How token refreshing ensures seamless user experience.

What is JWT?

JWT is a compact and self-contained token format used for securely transmitting information between parties as a JSON object. It consists of three parts:

  1. Header – Contains metadata like token type and signing algorithm.
  2. Payload – Stores claims (user information, expiry time, etc.).
  3. Signature – Ensures token integrity using a secret key.

Example of a JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiIxMjM0IiwiaWF0IjoxNjExNjE2MDB9.4xvNcTkORHj9xE8TftRkEw7sdJjxUX9PYG6xRJOnhZk
Enter fullscreen modeExit fullscreen mode

JWT is commonly used for authentication because it eliminates the need for session storage and repeated database queries.


Access & Refresh Tokens in CampusX

CampusX usesaccess tokens for authentication andrefresh tokens for renewing access tokens without requiring the user to log in again.

1. Generating Tokens

constgenerateAccessAndRefreshTokens=async(userId)=>{try{constuser=awaitUser.findById(userId);constaccessToken=user.generateAccessToken();constrefreshToken=user.generateRefreshToken();user.refreshToken=refreshToken;awaituser.save({validateBeforeSave:false});return{accessToken,refreshToken};}catch(error){thrownewApiError(STATUS_CODES.INTERNAL_ERROR,"Error generating access and refresh tokens");}};
Enter fullscreen modeExit fullscreen mode

Here, the user's access and refresh tokens are generated and stored securely.


JWT Authentication Middleware

TheverifyJWT middleware protects routes by verifying JWT tokens before allowing access.

exportconstverifyJWT=AsyncHandler(async(req,res,next)=>{try{consttoken=req.cookies?.accessToken||req.header("Authorization")?.replace("Bearer","");if(!token){thrownewApiError(401,"Unauthorized request");}constdecodedToken=jwt.verify(token,process.env.ACCESS_TOKEN_SECRET);constuser=awaitUser.findById(decodedToken._id).select("-password -refreshToken");if(!user){thrownewApiError(402,"Invalid access token");}req.user=user;next();}catch(error){thrownewApiError(401,"Token expired");}});
Enter fullscreen modeExit fullscreen mode

This ensures only authenticated users can access protected resources.


Refreshing Expired Tokens

If the access token expires, CampusX uses therefresh token to generate a new access token, avoiding user logouts.

constrefreshAccessToken=AsyncHandler(async(req,res)=>{constincomingRefreshToken=req.cookies.refreshToken||req.body.refreshToken;if(!incomingRefreshToken){thrownewApiError(STATUS_CODES.UNAUTHORIZED,"Refresh token not found");}try{constdecodedToken=jwt.verify(incomingRefreshToken,process.env.REFRESH_TOKEN_SECRET);constuser=awaitUser.findById(decodedToken._id);if(!user||incomingRefreshToken!==user.refreshToken){thrownewApiError(STATUS_CODES.UNAUTHORIZED,"Invalid refresh token");}const{accessToken,refreshToken}=awaitgenerateAccessAndRefreshTokens(user._id);res.status(STATUS_CODES.OK).cookie("accessToken",accessToken,{httpOnly:true,secure:true}).cookie("refreshToken",refreshToken,{httpOnly:true,secure:true}).json(newApiResponse(STATUS_CODES.OK,{accessToken,refreshToken},"Access token refreshed"));}catch(error){thrownewApiError(STATUS_CODES.INTERNAL_ERROR,"Error refreshing access token:"+error.message);}});
Enter fullscreen modeExit fullscreen mode

Fetching User on Page Refresh

CampusX callsfetchUser on every page load to refresh expired access tokens.

constfetchUser=async()=>{try{constres=awaitaxiosInstance.get("/users/current-user");setUser(res.data?.data?.user);}catch(err){if(err.response?.status===401){setUser(null);}if(err.response?.status===403){console.log("Access Token Expired, Refreshing...");try{awaitaxiosInstance.post("/users/refresh-token");returnfetchUser();// Retry the original request}catch(refreshErr){toast.error("Session expired, Please login again!");}}throwerr;}};
Enter fullscreen modeExit fullscreen mode

How it Works:

  1. Calls/users/current-user to check if the user is logged in.
  2. If theaccess token is expired (403 error), it tries to refresh it using/users/refresh-token.
  3. If refreshing fails, prompts the user to log in again.

Conclusion

JWT authentication in CampusX ensures:
✅ Secure user authentication.

✅ Efficient token-based session management.

✅ Seamless token refresh without re-login.

By implementingaccess & refresh tokens, CampusX provides a smooth user experience while maintaining strong security. 🚀

🔹Try implementing JWT authentication in your projects!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

🚀 A Passionate Web Developer | Building Scalable & Dynamic Applications💻 Full-stack developer exploring React, Node.js, and AI-powered projects. Constantly learning and sharing insights on web dev
  • Joined

More fromPrathviraj H

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp