
Authentication and Authorization in Node.js with JWT
Any online application must have security in order for users to safely log in and access resources without disclosing private information. JSON Web Tokens (JWT) are one of the most widely used methods for handling authorization and authentication in Node.js. JWT offers a condensed, standalone technique for safely sending data as a JSON object between parties.
This blog will discuss:
- The meaning of authorization and authentication.
- Why JWT is so popular.
- How to set up authentication in a Node.js application using JWT.
- JWT security best practices.
Authentication vs Authorization
Let’s define the distinction between authorization and authentication before moving on to implementation:
- Authentication, such as using a username and password to log in, confirms the identity of the user.
- After authentication, authorization controls the user’s access (e.g., allowing an admin user to remove records).
- JWT facilitates the effective management of both procedures in web applications.ations.
Why Use JWT for Authentication?
JWT is a popular authentication mechanism because:
- Stateless – No need to store session data on the server.
- Compact and Secure – Uses a signed token to transmit user data.
- Easy to Implement – Works well with RESTful APIs.
- Cross-Domain Support – Works across different platforms (mobile, web, backend services).
How JWT Works in Node.js
- The user logs in with their credentials.
- If valid, the server generates a JWT and sends it to the client.
- The client includes the token in the headers of future requests.
- The server verifies the token and grants or denies access to resources.
Setting Up JWT Authentication in Node.js
Let’s implement JWT authentication using Express.js and jsonwebtoken.
Step 1: Install Dependencies
Ensure you have Node.js installed, then run:
npm init -y # Initialize a new project
npm install express jsonwebtoken bcryptjs dotenv
express
: Web framework for Node.js.jsonwebtoken
: For generating and verifying JWTs.bcryptjs
: For hashing passwords.dotenv
: For environment variables.
Step 2: Create a Basic Express Server
Create server.js
and set up an Express app:
const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
app.use(express.json());
const users = []; // In-memory user storage (replace with DB in production)
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Step 3: User Registration
Hash the user’s password before storing it:
app.post("/register", async (req, res) => {
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" });
});
Step 4: User Login & Token Generation
Validate user credentials and issue a JWT:
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ message: "Invalid credentials" });
}
const token = jwt.sign({ username: user.username }, process.env.JWT_SECRET, { expiresIn: "1h" });
res.json({ token });
});
Step 5: Protect Routes with JWT Middleware
Create a middleware to verify JWT tokens:
const authenticateToken = (req, res, next) => {
const token = req.header("Authorization");
if (!token) return res.status(403).json({ message: "Access denied" });
jwt.verify(token.split(" ")[1], process.env.JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ message: "Invalid token" });
req.user = user;
next();
});
};
Step 6: Create a Protected Route
Only authenticated users can access this:
app.get("/protected", authenticateToken, (req, res) => {
res.json({ message: "Welcome to the protected route, " + req.user.username });
});
Best Practices for JWT Security
- Employ Powerful Secrets Use a strong key and keep your JWT_SECRET in a.env file.
- Set Token Expiry: Tokens with a short lifespan (expiresIn: “1h”) lower the possibility of abuse.
- Employ HTTPS: Secure connections guard against token interception.
- Blacklist Tokens on Logout: Take into account storing revoked tokens in a database.
- Use Refresh Tokens: Reauthenticate users by issuing long-lived refresh tokens.
In conclusion
One effective method for implementing permission and authentication in Node.js apps is JWT. You can maintain system security while maintaining a smooth user experience by adhering to recommended practices.
Leave a Reply