In web applications, Authentication and Authorization are critical for security:
Authentication – Verifies the identity of a user (login/signup).
Authorization – Determines what a user can access based on their role or permissions.
Express.js does not include built-in authentication, but you can implement it using middleware, JWT, Passport.js, or session-based methods.
Uses express-session to store user login sessions on the server.
Setup:
Example:
Uses JSON Web Tokens (JWT) to authenticate users.
Tokens are sent with each request instead of storing sessions on the server.
Setup:
Example:
Authorization determines what a logged-in user can do.
Often done by checking roles or permissions.
Example:
authenticateToken ensures the user is logged in
authorizeRole ensures the user has proper permissions
Never store plain passwords – always hash with bcrypt.
Use HTTPS to protect tokens and session cookies.
Keep JWT secrets secure and rotate periodically.
Implement role-based access control (RBAC) for authorization.
Use middleware to centralize authentication and authorization logic.
Set token expiration times and handle token refresh securely.
| Library | Use Case |
|---|---|
| Passport.js | Supports many strategies (JWT, OAuth, local) |
| jsonwebtoken | JWT-based token authentication |
| bcrypt | Password hashing |
| express-session | Session-based authentication |
User logs in → Credentials checked → Issue session or JWT.
Client sends request → Include token/session.
Server middleware verifies → Grant or deny access.
Authorization checks → Confirm user has permission.
Take quizzes related to this topic and see where you stand!
Start Quiz Now