Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Crafting a Secure Authentication System with JWT and middleware
Aneeqa Khan
Aneeqa Khan

Posted on

     

Crafting a Secure Authentication System with JWT and middleware

Table of Contents

For this series, I'm following an excellent video tutorial fromTraversy Media

Introduction

In this blog, we'll dive into the development of a robust authentication system for your application. We'll start by creating aprotect middleware that ensures the safety of our users' data.

Create protect middleware

Firstly, we'll start with creating anauthMiddleware.js file in themiddleware folder.

constjwt=require("jsonwebtoken");constasyncHandler=require("express-async-handler");constUser=require("../models/userModel");constprotect=asyncHandler(async(req,res,next)=>{lettoken;if(req.headers.authorization&&req.headers.authorization.startsWith("Bearer")){try{// get token from headertoken=req.headers.authorization.split("")[1];// verify tokenconstdecoded=jwt.verify(token,process.env.JWT_SECRET);// get user from the tokenreq.user=awaitUser.findById(decoded.id).select("-password");next();}catch(error){console.log(error);res.status(401);thrownewError("Not Authorized");}}if(!token){res.status(401);thrownewError("Not Authorized, no token");}});module.exports={protect};
Enter fullscreen modeExit fullscreen mode

In this function, we retrieve the token from the request headers and verify it to determine if the decoded token'sid matches any user in the database. If it doesn't find a user or if the token is missing, in such cases, we throw an error.

Get current user data

Next, we'll create a function to get the currently logged-in user data inuserController.js.

constgetLoggedInUser=asyncHandler(async(req,res)=>{const{_id,name,email}=awaitUser.findById(req.user.id);res.status(200).json({id:_id,name,email,});});
Enter fullscreen modeExit fullscreen mode

Protect the user data route

In the last, We'll useprotect middleware to secure the user data route. Add these lines to theuserRoutes.js file.

// import middlewareconst{protect}=require("../middleware/authMiddleware");...// Add a protect as a second paramrouter.get("/me",protect,getLoggedInUser);...
Enter fullscreen modeExit fullscreen mode

Now, let's check this functionality with no token

no jwt token

Now add the correct token

secure user data

And now test it with an invalid token

invalid token

That's it for today. In the next article, we'll work on protecting the todos routes.

Connect with me

Top comments(1)

Subscribe
pic
Create template

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

Dismiss
CollapseExpand
 
momin profile image
Md Abdul Momin
I'm a Front-End Software engineer who will be responsible for the complete lifecycle of scalable, secure, and well-designed software products from research and design to implementation.
  • Location
    Dhaka
  • Education
    BSc in EEE
  • Work
    Front-End Developer
  • Joined

A lot of things have to be learned and learned! Thanks

Could you add a frontendfolder/stracture so we can learn the structure and templating engine? I'm looking forejs

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

Software Engineer by profession, Artist by heart
  • Location
    London, United Kingdom
  • Education
    MCS
  • Pronouns
    she/her
  • Work
    Finding work
  • Joined

More fromAneeqa Khan

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