亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1. What is JWT?
2. Setup and Dependencies
3. Basic Server Setup
4. User Registration
5. User Login and Token Generation
6. Protected Route Example
7. Environment Variables
8. Testing the API
Important Security Notes
Optional: Refresh Tokens
Home Web Front-end JS Tutorial Implementing Authentication with JWT in a Node.js App

Implementing Authentication with JWT in a Node.js App

Aug 01, 2025 am 05:59 AM
jwt

JWT is a secure token format for authentication, consisting of header, payload, and signature; 2. Set up Node.js with Express, jsonwebtoken, bcryptjs, body-parser, and dotenv; 3. Create a server with user registration, password hashing, and login to generate JWT; 4. Implement token verification middleware to protect routes; 5. Store secrets in environment variables and use HTTPS in production; 6. Test registration, login, and access to protected routes using tools like curl or Postman; 7. Optionally implement refresh tokens for improved security and user experience; the system securely handles authentication using JWT in Node.js with Express and is ready for production when combined with a real database and proper security practices.

Implementing Authentication with JWT in a Node.js App

Adding authentication to a Node.js app using JSON Web Tokens (JWT) is a common and effective way to secure your APIs. Here's a practical guide to help you implement JWT-based authentication in a Node.js application using Express.

Implementing Authentication with JWT in a Node.js App

1. What is JWT?

JWT (JSON Web Token) is a compact, URL-safe token format used to securely transmit information between parties as a JSON object. It’s commonly used for authentication and authorization. A JWT typically consists of three parts: header, payload, and signature, separated by dots (e.g., xxx.yyy.zzz).

Once a user logs in, the server generates a JWT and sends it to the client. The client then includes this token in subsequent requests (usually in the Authorization header), and the server verifies it before granting access.

Implementing Authentication with JWT in a Node.js App

2. Setup and Dependencies

Start by initializing your Node.js project and installing required packages:

npm init -y
npm install express jsonwebtoken bcryptjs body-parser dotenv
npm install --save-dev nodemon
  • express: Web framework
  • jsonwebtoken: To generate and verify JWTs
  • bcryptjs: To hash passwords
  • body-parser: To parse incoming request bodies
  • dotenv: To manage environment variables

Add a script to package.json for development:

Implementing Authentication with JWT in a Node.js App
"scripts": {
  "start": "node server.js",
  "dev": "nodemon server.js"
}

3. Basic Server Setup

Create a server.js file:

const express = require('express');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

dotenv.config();

const app = express();
app.use(bodyParser.json());

// Simulated user database (use a real DB like MongoDB or PostgreSQL in production)
const users = [];

const SECRET_KEY = process.env.SECRET_KEY || 'your-super-secret-jwt-key';

// Utility: Generate JWT
const generateToken = (user) => {
  return jwt.sign({ id: user.id, username: user.username }, SECRET_KEY, {
    expiresIn: '1h',
  });
};

// Middleware: Authenticate token
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

  if (!token) {
    return res.status(401).json({ message: 'Access denied. No token provided.' });
  }

  jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) {
      return res.status(403).json({ message: 'Invalid or expired token.' });
    }
    req.user = user;
    next();
  });
};

4. User Registration

app.post('/register', async (req, res) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res.status(400).json({ message: 'Username and password are required.' });
  }

  // Check if user already exists
  const existingUser = users.find(u => u.username === username);
  if (existingUser) {
    return res.status(400).json({ message: 'Username already exists.' });
  }

  // Hash password
  const hashedPassword = await bcrypt.hash(password, 10);

  const user = { id: users.length   1, username, password: hashedPassword };
  users.push(user);

  res.status(201).json({ message: 'User registered successfully.' });
});

5. User Login and Token Generation

app.post('/login', async (req, res) => {
  const { username, password } = req.body;

  const user = users.find(u => u.username === username);
  if (!user) {
    return res.status(400).json({ message: 'Invalid credentials.' });
  }

  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) {
    return res.status(400).json({ message: 'Invalid credentials.' });
  }

  const token = generateToken(user);
  res.json({
    message: 'Login successful.',
    token,
  });
});

6. Protected Route Example

app.get('/profile', authenticateToken, (req, res) => {
  res.json({ message: `Welcome ${req.user.username}`, userId: req.user.id });
});

7. Environment Variables

Create a .env file:

SECRET_KEY=change-this-to-a-very-long-random-string-in-production

This keeps your secret key secure and outside your codebase.


8. Testing the API

You can test using curl or tools like Postman:

Register:

curl -X POST http://localhost:3000/register \
  -H "Content-Type: application/json" \
  -d '{"username":"alice", "password":"secret123"}'

Login:

curl -X POST http://localhost:3000/login \
  -H "Content-Type: application/json" \
  -d '{"username":"alice", "password":"secret123"}'

Access protected route:

curl -X GET http://localhost:3000/profile \
  -H "Authorization: Bearer <your-jwt-token>"

Important Security Notes

  • ? Always use HTTPS in production.
  • ? Store the JWT secret in environment variables — never hardcode it.
  • ? Set a reasonable token expiration (e.g., 15–60 minutes). Use refresh tokens for long-lived sessions.
  • ? Validate and sanitize all inputs to prevent injection attacks.
  • ?? In production, use a real database with proper indexing and security.

Optional: Refresh Tokens

For better UX, implement refresh tokens to renew access tokens without requiring re-login. This adds complexity but improves security and usability.


That’s it! You now have a working JWT authentication system in Node.js. It’s minimal but covers the essentials: registration, login, token generation, verification, and protected routes.

Basically just glue the pieces together securely — and never skip hashing passwords.

The above is the detailed content of Implementing Authentication with JWT in a Node.js App. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Analysis of secure JWT token generation and verification technology in PHP Analysis of secure JWT token generation and verification technology in PHP Jul 01, 2023 pm 06:06 PM

Analysis of Secure JWT Token Generation and Verification Technology in PHP With the development of network applications, user authentication and authorization are becoming more and more important. JsonWebToken (JWT) is an open standard (RFC7519) for securely transmitting information in web applications. In PHP development, it has become a common practice to use JWT tokens for user authentication and authorization. This article will introduce secure JWT token generation and verification technology in PHP. 1. Basic knowledge of JWT in understanding how to generate and

How to use ThinkPHP6 for JWT authentication? How to use ThinkPHP6 for JWT authentication? Jun 12, 2023 pm 12:18 PM

JWT (JSONWebToken) is a lightweight authentication and authorization mechanism that uses JSON objects as security tokens to securely transmit user identity information between multiple systems. ThinkPHP6 is an efficient and flexible MVC framework based on PHP language. It provides many useful tools and functions, including JWT authentication mechanism. In this article, we will introduce how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications

OAuth in PHP: Create a JWT authorization server OAuth in PHP: Create a JWT authorization server Jul 28, 2023 pm 05:27 PM

OAuth in PHP: Creating a JWT authorization server With the rise of mobile applications and the trend of separation of front-end and back-end, OAuth has become an indispensable part of modern web applications. OAuth is an authorization protocol that protects users' resources from unauthorized access by providing standardized processes and mechanisms. In this article, we will learn how to create a JWT (JSONWebTokens) based OAuth authorization server using PHP. JWT is a type of

How to use JWT and JWE for API authentication and encryption in PHP How to use JWT and JWE for API authentication and encryption in PHP Jun 17, 2023 pm 02:42 PM

With the development of the Internet, more and more websites and applications need to provide API interfaces for data interaction. In this case, API authentication and encryption become very important issues. As a popular authentication and encryption mechanism, JWT and JWE are increasingly used in PHP. Well, this article will explain how to use JWT and JWE for API authentication and encryption in PHP. Basic concepts of JWT JWT stands for JSONWe

A complete guide to implementing login authentication in Vue.js (API, JWT, axios) A complete guide to implementing login authentication in Vue.js (API, JWT, axios) Jun 09, 2023 pm 04:04 PM

Vue.js is a popular JavaScript framework for building dynamic web applications. Implementing user login authentication is one of the necessary parts of developing web applications. This article will introduce a complete guide to implementing login verification using Vue.js, API, JWT and axios. Creating a Vue.js Application First, we need to create a new Vue.js application. We can create a Vue.js application using VueCLI or manually. Install axiosax

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Using JWT to implement authentication in Beego Using JWT to implement authentication in Beego Jun 22, 2023 pm 12:44 PM

With the rapid development of the Internet and mobile Internet, more and more applications require authentication and permission control, and JWT (JSON Web Token), as a lightweight authentication and authorization mechanism, is widely used in WEB applications. Beego is an MVC framework based on the Go language, which has the advantages of efficiency, simplicity, and scalability. This article will introduce how to use JWT to implement authentication in Beego. 1. Introduction to JWT JSONWebToken (JWT) is a

How SpringBoot combines JWT to implement login permission control How SpringBoot combines JWT to implement login permission control May 20, 2023 am 11:01 AM

First we need to import the jwt package used: io.jsonwebtokenjjwt0.8.0com.auth0java-jwt3.2.0 1. Prepare LoginUser (store login user information) and JwtUserLoginUser.javapublicclassLoginUser{privateIntegeruserId;privateStringusername;privateStringpassword;privateStringrole;generate getters and setters ...}JwtUser.javaimp

See all articles