Home >Web Front-end >JS Tutorial >User Authentication API with Express, JWT, Bcrypt, and MySQL
This application is a simple authentication server built with Express, using JSON Web Tokens (JWT) for session management and bcrypt for securely storing passwords. Users can register and log in to access protected routes. MySQL is used for storing user data.
1. Express.js: Web framework for handling routes and middleware.
2. bcrypt.js: Library for hashing passwords securely.
3. jsonwebtoken: Library for creating and verifying JWT tokens.
4. mysql2: MySQL client for Node.js with support for Promises.
5. cookie-parser: Middleware for parsing cookies.
1. Import Required Libraries
const express = require('express'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const cookieParser = require('cookie-parser'); const mysql = require('mysql2/promise');
const app = express(); const PORT = 3000; const JWT_SECRET = 'your_jwt_secret_key';
const db = await mysql.createConnection({ host: 'localhost', user: 'your_mysql_user', password: 'your_mysql_password', database: 'user_auth' });
app.use(express.json()); app.use(cookieParser());
/register
This route registers a new user by hashing their password and saving it in the database.
const express = require('express'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const cookieParser = require('cookie-parser'); const mysql = require('mysql2/promise');
/login
This route logs in an existing user by checking their credentials and generating a JWT token.
const app = express(); const PORT = 3000; const JWT_SECRET = 'your_jwt_secret_key';
The verifyToken middleware ensures that only requests with a valid JWT token can access protected routes.
const db = await mysql.createConnection({ host: 'localhost', user: 'your_mysql_user', password: 'your_mysql_password', database: 'user_auth' });
A sample protected route accessible only to authenticated users. It returns a personalized greeting using the user’s name from the token.
app.use(express.json()); app.use(cookieParser());
The server listens on the defined PORT.
app.post('/register', async (req, res) => { const { name, email, password } = req.body; try { // Check if user already exists const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]); if (rows.length > 0) { return res.status(400).json({ message: 'User already exists' }); } // Hash the password const hashedPassword = await bcrypt.hash(password, 10); // Save the user in the database await db.execute('INSERT INTO users (name, email, password) VALUES (?, ?, ?)', [name, email, hashedPassword]); res.status(201).json({ message: 'User registered successfully!' }); } catch (error) { console.error(error); res.status(500).json({ message: 'Server error' }); } });
app.post('/login', async (req, res) => { const { email, password } = req.body; try { // Find user const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]); const user = rows[0]; if (!user) { return res.status(400).json({ message: 'User not found' }); } // Check password const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) { return res.status(400).json({ message: 'Invalid credentials' }); } // Create JWT token const token = jwt.sign({ id: user.id, name: user.name, email: user.email }, JWT_SECRET, { expiresIn: '1h' }); // Set JWT in cookie res.cookie('token', token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'Strict', maxAge: 3600000 // 1 hour }); res.json({ message: 'Logged in successfully!' }); } catch (error) { console.error(error); res.status(500).json({ message: 'Server error' }); } });
This application:
The above is the detailed content of User Authentication API with Express, JWT, Bcrypt, and MySQL. For more information, please follow other related articles on the PHP Chinese website!