Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8955

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T05:55:06+00:00 2024-11-28T05:55:06+00:00

Creating and Securing JWT Authentication in a Web App

  • 60k

Introduction

JSON Web Tokens (JWT) are a compact and self-contained way of securely transmitting information between parties as a JSON object. JWTs are widely used for authenticating users in web applications. In this tutorial, we’ll build a Node.js and Express backend with JWT authentication.

What is JWT?

JWT (JSON Web Token) is an open standard for securely transmitting information between parties as a JSON object. Each token consists of three parts:

  1. Header: Contains information about the token's type and hashing algorithm.
  2. Payload: Contains user information and claims.
  3. Signature: Verifies the integrity of the token.

Example JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0IiwidXNlcm5hbWUiOiJqb2huZG9lIn0.H6BBiB1y5eXKXvW9bbjT2Rg8Jp4oE4Y5Kxf_sDF7Kzg 
Enter fullscreen mode Exit fullscreen mode

Setting Up the Project

  1. Create a new project directory:

    mkdir jwt-auth-app cd jwt-auth-app 
  2. Initialize a new Node.js project:

    npm init -y 

Installing Dependencies

Install the necessary dependencies:

npm install express jsonwebtoken bcryptjs dotenv express-validator 
Enter fullscreen mode Exit fullscreen mode

  • express: Web framework for Node.js.
  • jsonwebtoken: Library for generating and verifying JWTs.
  • bcryptjs: Library for hashing passwords.
  • dotenv: For environment variables.
  • express-validator: For validating input data.

Configuring the Server

Create a basic server setup in server.js:

// server.js require('dotenv').config(); const express = require('express'); const app = express(); app.use(express.json());  // Import Routes const authRoutes = require('./routes/auth'); app.use('/api/auth', authRoutes);  const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); 
Enter fullscreen mode Exit fullscreen mode

Create a .env file for storing environment variables:

PORT=5000 JWT_SECRET=your_jwt_secret_key 
Enter fullscreen mode Exit fullscreen mode

Creating User Authentication Routes

  1. Create the routes/auth.js file for authentication routes:
// routes/auth.js const express = require('express'); const { body, validationResult } = require('express-validator'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const router = express.Router();  const users = []; // In-memory user storage  // Signup Route router.post(   '/signup',   [     body('username').isLength({ min: 3 }),     body('password').isLength({ min: 5 })   ],   async (req, res) => {     const errors = validationResult(req);     if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });      const { username, password } = req.body;     const hashedPassword = await bcrypt.hash(password, 10);      users.push({ username, password: hashedPassword });     res.status(201).json({ message: 'User registered successfully' });   } );  // Login Route router.post(   '/login',   [     body('username').notEmpty(),     body('password').notEmpty()   ],   async (req, res) => {     const errors = validationResult(req);     if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });      const { username, password } = req.body;     const user = users.find(u => u.username === username);      if (!user) return res.status(400).json({ message: 'Invalid credentials' });      const isMatch = await bcrypt.compare(password, user.password);     if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });      const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });     res.json({ token });   } );  module.exports = router; 
Enter fullscreen mode Exit fullscreen mode

  1. Explanation of Routes
  • Signup Route: Validates and hashes the password before storing the user.
  • Login Route: Validates credentials, checks password, and issues a JWT token.

Generating JWT Tokens

  • The jwt.sign method generates a token containing the user’s information.
  • The JWT_SECRET is used to sign the token, which should be kept secure and private.
const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' }); 
Enter fullscreen mode Exit fullscreen mode

Securing Routes with JWT

To protect routes, create a middleware to verify tokens.

  1. Create middleware/auth.js:
// middleware/auth.js const jwt = require('jsonwebtoken');  module.exports = function (req, res, next) {   const token = req.header('Authorization')?.split(' ')[1];   if (!token) return res.status(401).json({ message: 'Access denied' });    try {     const decoded = jwt.verify(token, process.env.JWT_SECRET);     req.user = decoded;     next();   } catch (ex) {     res.status(400).json({ message: 'Invalid token' });   } }; 
Enter fullscreen mode Exit fullscreen mode

  1. Protect Routes in server.js:

Create a protected route that requires a valid token:

// In server.js const authMiddleware = require('./middleware/auth');  app.get('/api/protected', authMiddleware, (req, res) => {   res.json({ message: 'This is a protected route', user: req.user }); }); 
Enter fullscreen mode Exit fullscreen mode

Explanation of Middleware

  • The middleware checks for the presence of the token in the Authorization header.
  • If the token is valid, the user’s information is added to the req object, allowing access to the protected route.

Conclusion

In this tutorial, we’ve covered the basics of setting up JWT authentication in a Node.js and Express backend. This guide demonstrated:

  1. Setting up authentication routes for signup and login.
  2. Creating and verifying JWT tokens.
  3. Securing routes with a JWT-based middleware.

JWTs are a powerful way to handle authentication, making your web applications both secure and scalable.

javascripttutorialtypescriptwebdev
  • 0 0 Answers
  • 7 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.