jwt-authentication
Implement secure JWT (JSON Web Token) authentication in Node.js applications with access/refresh tokens and role-based access control
What this skill does
# JWT Authentication Skill
Implement secure, scalable authentication in Node.js applications using JSON Web Tokens.
## Quick Start
JWT authentication in 4 steps:
1. **Install** - `npm install jsonwebtoken bcryptjs`
2. **Register** - Hash password, create user, generate token
3. **Login** - Verify password, generate token
4. **Protect** - Verify token in middleware
## Core Concepts
### Generate JWT
```javascript
const jwt = require('jsonwebtoken');
function generateToken(userId) {
return jwt.sign(
{ id: userId },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
}
function generateRefreshToken(userId) {
return jwt.sign(
{ id: userId },
process.env.JWT_REFRESH_SECRET,
{ expiresIn: '7d' }
);
}
```
### User Registration
```javascript
const bcrypt = require('bcryptjs');
async function register(req, res) {
const { email, password, name } = req.body;
// Check if user exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(409).json({ error: 'User already exists' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Create user
const user = await User.create({
email,
password: hashedPassword,
name
});
// Generate tokens
const accessToken = generateToken(user._id);
const refreshToken = generateRefreshToken(user._id);
res.status(201).json({
user: { id: user._id, email, name },
accessToken,
refreshToken
});
}
```
### User Login
```javascript
async function login(req, res) {
const { email, password } = req.body;
// Find user
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Verify password
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Generate tokens
const accessToken = generateToken(user._id);
const refreshToken = generateRefreshToken(user._id);
res.json({
user: { id: user._id, email: user.email },
accessToken,
refreshToken
});
}
```
### Authentication Middleware
```javascript
async function authenticate(req, res, next) {
try {
// Get token from header
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.split(' ')[1];
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Get user
const user = await User.findById(decoded.id).select('-password');
if (!user) {
return res.status(401).json({ error: 'User not found' });
}
req.user = user;
next();
} catch (error) {
res.status(401).json({ error: 'Invalid token' });
}
}
// Usage
router.get('/profile', authenticate, getProfile);
```
## Learning Path
### Beginner (1-2 weeks)
- ✅ Understand JWT structure
- ✅ Implement registration/login
- ✅ Create authentication middleware
- ✅ Protect routes
### Intermediate (3-4 weeks)
- ✅ Refresh token flow
- ✅ Role-based access control
- ✅ Password reset flow
- ✅ Token blacklisting
### Advanced (5-6 weeks)
- ✅ OAuth integration
- ✅ Two-factor authentication
- ✅ Session management
- ✅ Security best practices
## Advanced Patterns
### Role-Based Access Control
```javascript
const authorize = (...roles) => {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
};
// Usage
router.delete('/users/:id',
authenticate,
authorize('admin', 'moderator'),
deleteUser
);
```
### Token Refresh
```javascript
async function refreshAccessToken(req, res) {
const { refreshToken } = req.body;
try {
const decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);
// Verify refresh token exists in database
const stored = await RefreshToken.findOne({
token: refreshToken,
userId: decoded.id
});
if (!stored) {
return res.status(401).json({ error: 'Invalid refresh token' });
}
// Generate new access token
const accessToken = generateToken(decoded.id);
res.json({ accessToken });
} catch (error) {
res.status(401).json({ error: 'Token refresh failed' });
}
}
```
### Password Reset Flow
```javascript
async function requestPasswordReset(req, res) {
const { email } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Generate reset token (short expiry)
const resetToken = jwt.sign(
{ id: user._id, purpose: 'reset' },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
);
// Send email with reset link
await sendResetEmail(user.email, resetToken);
res.json({ message: 'Reset email sent' });
}
async function resetPassword(req, res) {
const { token, newPassword } = req.body;
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
if (decoded.purpose !== 'reset') {
return res.status(400).json({ error: 'Invalid token' });
}
const hashedPassword = await bcrypt.hash(newPassword, 10);
await User.findByIdAndUpdate(decoded.id, { password: hashedPassword });
res.json({ message: 'Password reset successful' });
} catch (error) {
res.status(400).json({ error: 'Invalid or expired token' });
}
}
```
## Security Best Practices
- ✅ Use strong JWT secrets (32+ characters, random)
- ✅ Short expiry for access tokens (15min - 1h)
- ✅ Longer expiry for refresh tokens (7d - 30d)
- ✅ Store refresh tokens in database
- ✅ Hash passwords with bcrypt (10+ rounds)
- ✅ Use HTTPS in production
- ✅ Implement rate limiting
- ✅ Validate all inputs
- ✅ Don't store sensitive data in JWT payload
## JWT Structure
```
header.payload.signature
Header (base64):
{
"alg": "HS256",
"typ": "JWT"
}
Payload (base64):
{
"id": "user123",
"iat": 1516239022,
"exp": 1516242622
}
Signature:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
```
## Common JWT Claims
- `iss` - Issuer
- `sub` - Subject (user ID)
- `aud` - Audience
- `exp` - Expiration time
- `iat` - Issued at
- `nbf` - Not before
## When to Use
Use JWT authentication when:
- Building stateless REST APIs
- Need scalability (no server-side sessions)
- Mobile app authentication
- Microservices architecture
- Single sign-on (SSO)
## Related Skills
- Express REST API (protect API endpoints)
- Database Integration (store users)
- Testing & Debugging (test auth flows)
- Performance Optimization (token caching)
## Resources
- [JWT.io](https://jwt.io)
- [OWASP Authentication Guide](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
- [bcrypt Documentation](https://www.npmjs.com/package/bcryptjs)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.