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:
- Header – Contains metadata like token type and signing algorithm.
- Payload – Stores claims (user information, expiry time, etc.).
- Signature – Ensures token integrity using a secret key.
Example of a JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiIxMjM0IiwiaWF0IjoxNjExNjE2MDB9.4xvNcTkORHj9xE8TftRkEw7sdJjxUX9PYG6xRJOnhZk
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");}};
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");}});
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);}});
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;}};
How it Works:
- Calls
/users/current-user
to check if the user is logged in. - If theaccess token is expired (403 error), it tries to refresh it using
/users/refresh-token
. - 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)
For further actions, you may consider blocking this person and/orreporting abuse