| name | api-authentication |
| description | Implement secure API authentication with JWT, OAuth 2.0, API keys, and session management. Use when securing APIs, managing tokens, or implementing user authentication flows. |
API Authentication
Overview
Implement comprehensive authentication strategies for APIs including JWT tokens, OAuth 2.0, API keys, and session management with proper security practices.
When to Use
- Securing API endpoints
- Implementing user login/logout flows
- Managing access tokens and refresh tokens
- Integrating OAuth 2.0 providers
- Protecting sensitive data
- Implementing API key authentication
Instructions
1. JWT Authentication
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const app = express();
const SECRET_KEY = process.env.JWT_SECRET || 'your-secret-key';
const REFRESH_SECRET = process.env.REFRESH_SECRET || 'your-refresh-secret';
app.(, (req, res) => {
{
{ email, password } = req.;
user = .({ email });
(!user) {
res.().({ : });
}
isValid = bcrypt.(password, user.);
(!isValid) {
res.().({ : });
}
accessToken = jwt.(
{ : user., : user., : user. },
,
{ : }
);
refreshToken = jwt.(
{ : user. },
,
{ : }
);
.({ : refreshToken, : user. });
res.({
accessToken,
refreshToken,
: ,
: { : user., : user., : user. }
});
} (error) {
res.().({ : });
}
});
app.(, {
{ refreshToken } = req.;
(!refreshToken) {
res.().({ : });
}
{
decoded = jwt.(refreshToken, );
storedToken = .({
: refreshToken,
: decoded.
});
(!storedToken) {
res.().({ : });
}
newAccessToken = jwt.(
{ : decoded. },
,
{ : }
);
res.({ : newAccessToken, : });
} (error) {
res.().({ : });
}
});
= () => {
authHeader = req.[];
token = authHeader && authHeader.()[];
(!token) {
res.().({ : });
}
{
decoded = jwt.(token, );
req. = decoded;
();
} (error) {
(error. === ) {
res.().({ : , : });
}
res.().({ : });
}
};
app.(, verifyToken, {
res.({ : req. });
});
app.(, verifyToken, (req, res) => {
{
.({ : req.. });
res.({ : });
} (error) {
res.().({ : });
}
});