Authentication and JWT in Node.js (2024)

Alright so this week I'm going to continue working with node. This one should be pretty short and sweet but I'd like to cover how to build out a login request and how to produce a token for verification in the front end. Let's get started.

What's required

So for our form of authentication I'm going to be using Bcrypt and a JWT. What are those you ask? I'm glad you asked.

Bcrypt: A function that uses an algorithm to hash passwords. This is important for user security because if someone were to gain access to your database and the passwords are not hashed the users credentials are compromised.

JWT: JWT stands for JSON Web Token. It is a standard for authentication in applications. Upon a successful login the server sends a JWT to the client as proof of verification. Think of this as the ticket for a user to gain access to gated content or personal content.

Now that we know what the pieces of the puzzle we will be using are lets go ahead and install them:

Once they're installed go ahead and require them in whatever file you will be applying authentication to. I will be doing it in my users route.

const bcrypt = require('bcrypt');const jwt = require('jsonwebtoken');

We're good to go.

Build it out

Creating a Hashed Password

So the first thing I'd like to handle is making sure when a user signs up we don't store their password in our database as is, that's just not cool. We have to hash it first. That's where bcrypt comes in. It will not only hash a password for us but it will also help verify hashed passwords.

Here is what my creating a user function will look like:

router.post('/add-user', async (req, res) => { try { const hashedPassword = await bcrypt.hash(req.body.password, 10); const user = new User({ username: req.body.username, password: hashedPassword, }); const savedUser = await user.save(); res.json(savedUser); } catch(e) { res.json({ message: "Error"}); }});

So let's break that down.

  • We created an async post request to our users route for adding a new user.
  • Since it is an async function we handle it within a try/catch block.
  • In the try block we create a hashedPassword constant and let bcrypt create a hashed password. It takes in the password from the request as well as the amount of saltRounds, we set that to 10 which I believe is the default. This is asynchronous so use an await.

Sidenote: Salt is used in cryptography. It is random data to mix in with the core data to ensure improbability of replication.

  • Once we have used bcrypt to create a hashed password we continue like a general post request. Create a user instance with the username and the newly created hashed password instead of the request password.
  • Save this new user instance with the hashed password.
  • In the catch block I have it set so if there is an error it will send a response with the error in JSON format.

Awesome. Now if you make a post and create a new user and go check out the database you will see in the password parameter it is a random string. Try and decode a password from that. You can't.

Logging a User In

Alright so now that we know how create users with hashed passwords in our database let's check out how to login a user.

For this portion we need Bcrypt to handle the hashed password and JWT to provide proof of successful verification. Again I do this in my users route.

First thing let's create a token secret in our .env file for later. This should be a random string that's totally unpredictable you can use the web to generate one. Store it in something like:

TOKEN_SECRET=b91028378997c0b3581821456edefd0ec7958f953f8c1a6dd856e2de27f0d7e0fb1a01cda20d1a6890267e629f0ff5dc7ee46bce382aba62d13989614417606a

Now let's check out the function:

router.post('/login', async (req, res) => { const user = await User.findOne({ username: req.body.username }); try{ const match = await bcrypt.compare(req.body.password, user.password); const accessToken = jwt.sign(JSON.stringify(user), process.env.TOKEN_SECRET) if(match){ res.json({ accessToken: accessToken }); } else { res.json({ message: "Invalid Credentials" }); } } catch(e) { console.log(e) }});

What's going on here:

  • It is again an async post request to our users route.
  • First thing we can do is find a user based on their username which ideally will be unique. This is done through using findOne on our User model via mongoose as we have in a previous blog post.
  • We create our try/catch block since again this is an async function.
  • First in our try black we will asynchronously compare the password we received in the request to the hashed one stored in the database using bcryt.compare and passing in first the request password and then the hashed password associated with the user we stored in a constant earlier. Bcrypt will compare and handle the hashing and provide a true or false value.
  • We will also be creating a token using JWT. We use jwt.sign() and pass in first the user data and that token secret we hid in our .env file.
  • Set up an if block and if the match is true it will return that token in a JSON formatted response.
  • If it is not a match it will respond with a message saying that the credentials are invalid.

You should at this point be able to test out a login POST request with a previously created user. If the password and username are correct the response should provide a JWT token as proof of verification. If not you should hit the error message.

Wrap Up

On the back-end you should now have an idea how to safely store users credentials as well as how to verify them and providing proof of verification via a JWT. Now locking content behind authentication and providing authorization is a front-end matter and something we won't be getting into today.

I hope you learned something today and if you have any questions/comments please feel free to reach out.
As always happy coding!

Authentication and JWT in Node.js (2024)

FAQs

Is JWT authentication enough? ›

It's important to note that a JWT guarantees data ownership but not encryption. The reason is that the JWT can be seen by anyone who intercepts the token because it's serialized, not encrypted.

Why JWTs are bad for authentication? ›

JWTs which just store a simple session token are inefficient and less flexible than a regular session cookie, and don't gain you any advantage. The JWT specification itself is not trusted by security experts. This should preclude all usage of them for anything related to security and authentication.

How to use JWT for authentication in node? ›

To use JWT in a Node. js application with Express. js, we need to create middleware that checks for the presence of a JWT in the request headers, verifies it, and then proceeds with the request. If the token is invalid or expired, the middleware should return an error response.

What is the best authentication method in node JS? ›

2FA/MFA: The highest level of authentication in Node is known as 2FA/MFA or two-factor authentication/multi-factor authentication. Authenticating the user requires additional PIN or security questions. One-time password: Access to numerous applications can be made possible by using single sign-on or SSO.

Which is better than JWT authentication? ›

Paseto (Platform-Agnostic Security Tokens) has emerged as a better solution, directly addressing the shortcomings of JWT. Designed with a focus on security, Paseto provides a more secure foundation for token-based authentication by mitigating vulnerabilities and enforcing secure defaults.

Is JWT good for API authentication? ›

Any API that requires authentication can easily switch over to JWT's authorization. With JWT authorization, you get a user-based authentication. Once the user is authenticated, the user gets a secure token that they can use on all systems. The management of the user (and therefore the token) is centralized.

What are the weaknesses of JWT? ›

Disadvantages of JWT Authentication:

Revoking a JWT before expiration requires additional complexity, such as token blacklisting. Security Risks: If the secret key used to sign JWTs is compromised, attackers can create forged tokens. It's crucial to safeguard this key.

Is JWT obsolete? ›

In May 2023, Adobe announced the deprecation and end of life of Service Account (JWT) credentials. This means that any of your integrations or custom applications using a Service Account (JWT) credential will need to migrate to the new OAuth Server-to-Server credential before January 27, 2025.

What are the risks of JWT authentication? ›

Exploring JWT Token Vulnerabilities:
  • Information Leakage:
  • Injection of New Public Key in Token Header:
  • None Algorithm Attack:
  • KID Parameter Attack:
  • Changing the Algorithm:
  • Sensitive Information Disclosure:
  • Compromised Client Authenticity:
  • Account Takeover:
Mar 14, 2024

How to use JWT and Node.js for better app security? ›

How to Use JWT and Node. js for Better App Security
  1. /API_PREFIX/users GET : Get all users ( PROTECTED )
  2. /API_PREFIX/users POST : Create a new user.
  3. /API_PREFIX/users/{ID} DELETE : Delete a specific user ( PROTECTED )
  4. /API_PREFIX/users/{ID} PATCH : Update a specific user ( PROTECTED )

How do you verify a JWT token in node? ›

JWT verify method is used for verify the token the take two arguments one is token string value, and second one is secret key for matching the token is valid or not. The validation method returns a decode object that we stored the token in.

How does JWT authentication work in REST API? ›

When using a JWT, the client first authenticates with the server. The server then responds with a JWT. The client then includes the JWT in subsequent requests to the server. The server can then use the JWT to verify the identity of the client.

Which is the most powerful authentication method? ›

Categories
  • The Three Types of Authentication Factors.
  • Least Secure: Passwords.
  • More Secure: One-time Passwords.
  • More Secure: Biometrics.
  • Most Secure: Hardware Keys.
  • Most Secure: Device Authentication and Trust Factors.
Jul 22, 2024

What is the strongest authentication? ›

Physical security key

A physical authentication key is one of the strongest ways to implement multifactor authentication. A private key, stored on a physical device, is used to authenticate a user, such as a USB device that a user plugs into their computer while logging in.

What is the best API for authentication? ›

Best API authentication protocols
  1. OAuth (Open Authorization) OAuth is an industry-standard authentication protocol that allows secure access to resources on behalf of a user or application. ...
  2. Bearer tokens. Bearer tokens are a simple way to authenticate API requests. ...
  3. API keys. ...
  4. JSON Web Tokens (JWT) ...
  5. Basic authentication.
Oct 25, 2023

What are the disadvantages of JWT authentication? ›

Disadvantages of JWT Authentication:

Revoking a JWT before expiration requires additional complexity, such as token blacklisting. Security Risks: If the secret key used to sign JWTs is compromised, attackers can create forged tokens. It's crucial to safeguard this key.

Should I use JWT for authorization? ›

Use traditional session-based authentication. It's more secure and flexible than JWT. JWT is a good fit for cases/situations where you want to issue a one-time token to be used for a specific purpose.

How much secure is JWT? ›

JWTs are self-contained, by-value tokens and it is very hard to revoke them, once issued and delivered to the recipient. Because of that, you should use as short an expiration time for your tokens as possible. A best practice is to set your JWT expiration to minutes or hours at maximum.

Top Articles
Top 15 Most Popular Project Charts for Project Management | Nifty Blog
UTXO
Chs.mywork
NYT Mini Crossword today: puzzle answers for Tuesday, September 17 | Digital Trends
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
4-Hour Private ATV Riding Experience in Adirondacks 2024 on Cool Destinations
Http://N14.Ultipro.com
Phone Number For Walmart Automotive Department
Chalupp's Pizza Taos Menu
Zitobox 5000 Free Coins 2023
Www Thechristhospital Billpay
Mivf Mdcalc
Ktbs Payroll Login
4Chan Louisville
Obituary | Shawn Alexander | Russell Funeral Home, Inc.
Yesteryear Autos Slang
Rosemary Beach, Panama City Beach, FL Real Estate & Homes for Sale | realtor.com®
Premier Reward Token Rs3
Salem Oregon Costco Gas Prices
The Pretty Kitty Tanglewood
Shopmonsterus Reviews
Shiftselect Carolinas
Maxpreps Field Hockey
A Person That Creates Movie Basis Figgerits
Timeline of the September 11 Attacks
Papa Johns Mear Me
New Stores Coming To Canton Ohio 2022
Goodwill Of Central Iowa Outlet Des Moines Photos
Wku Lpn To Rn
Craigslist Fort Smith Ar Personals
The Collective - Upscale Downtown Milwaukee Hair Salon
Xxn Abbreviation List 2023
Bend Missed Connections
Housing Assistance Rental Assistance Program RAP
Save on Games, Flamingo, Toys Games & Novelties
Nacho Libre Baptized Gif
Whitehall Preparatory And Fitness Academy Calendar
20+ Best Things To Do In Oceanside California
Frcp 47
Daly City Building Division
Citibank Branch Locations In Orlando Florida
888-822-3743
Pathfinder Wrath Of The Righteous Tiefling Traitor
Petra Gorski Obituary (2024)
Elven Steel Ore Sun Haven
CrossFit 101
The Sports Academy - 101 Glenwest Drive, Glen Carbon, Illinois 62034 - Guide
House For Sale On Trulia
La Fitness Oxford Valley Class Schedule
Latest Posts
Article information

Author: Carlyn Walter

Last Updated:

Views: 6714

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Carlyn Walter

Birthday: 1996-01-03

Address: Suite 452 40815 Denyse Extensions, Sengermouth, OR 42374

Phone: +8501809515404

Job: Manufacturing Technician

Hobby: Table tennis, Archery, Vacation, Metal detecting, Yo-yoing, Crocheting, Creative writing

Introduction: My name is Carlyn Walter, I am a lively, glamorous, healthy, clean, powerful, calm, combative person who loves writing and wants to share my knowledge and understanding with you.