1. JWT Typing
JSON Web Tokens (JWT) are commonly used for authentication. TypeScript allows typing the token payload to ensure type safety.
Installation
npm install jsonwebtoken
npm install --save-dev @types/jsonwebtoken
Typing JWT Payload
import jwt, { JwtPayload } from "jsonwebtoken";
interface MyJwtPayload extends JwtPayload {
userId: number;
role: string;
}
const token = jwt.sign({ userId: 1, role: "admin" }, "secret", { expiresIn: "1h" });
const decoded = jwt.verify(token, "secret") as MyJwtPayload;
console.log(decoded.userId, decoded.role);
Typing the JWT payload ensures correct access to properties and reduces runtime errors.
2. Role-Based Access Control (RBAC)
RBAC restricts access to resources based on user roles.
Example Middleware
import { Request, Response, NextFunction } from "express";
const authorize = (roles: string[]) => (req: Request, res: Response, next: NextFunction) => {
const userRole = req.user?.role; // assuming req.user is populated after JWT verification
if (!roles.includes(userRole)) {
return res.status(403).json({ message: "Access denied" });
}
next();
};
// Usage
app.get("/admin", authorize(["admin"]), (req, res) => {
res.send("Welcome, admin");
});
RBAC ensures that only authorized users can access sensitive endpoints.
3. Secure Middleware
Middleware can enforce authentication and attach user info to requests.
JWT Authentication Middleware
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
interface JwtRequest extends Request {
user?: { userId: number; role: string };
}
const authenticate = (req: JwtRequest, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ message: "No token provided" });
try {
const decoded = jwt.verify(token, "secret") as { userId: number; role: string };
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ message: "Invalid token" });
}
};
app.use(authenticate);
Secure middleware ensures that requests are properly authenticated and authorized before reaching route handlers.
Conclusion
Implementing authentication and authorization in TypeScript using JWT, role-based access, and secure middleware provides robust security for APIs. Typed tokens and middleware enhance type safety, reduce runtime errors, and ensure that applications are both safe and maintainable.