
jwt-authentication
Implement secure JWT (JSON Web Token) authentication in Node.js applications with access/refresh tokens and role-based access control
- Installs
- 226
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill jwt-authentication- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads jwt-authentication automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
JWT Authentication Skill
Implement secure, scalable authentication in Node.js applications using JSON Web Tokens.
Quick Start
JWT authentication in 4 steps:
- Install -
npm install jsonwebtoken bcryptjs - Register - Hash password, create user, generate token
- Login - Verify password, generate token
- Protect - Verify token in middleware
Core Concepts
Generate JWT
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
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
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
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
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
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
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- Issuersub- Subject (user ID)aud- Audienceexp- Expiration timeiat- Issued atnbf- 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
FAQ
What does the jwt-authentication skill do?
Implement secure JWT (JSON Web Token) authentication in Node.js applications with access/refresh tokens and role-based access control
How do I install jwt-authentication?
Run npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill jwt-authentication in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/jwt-authentication/ (personal) or .claude/skills/jwt-authentication/ (project).
Which AI agents can use jwt-authentication?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is jwt-authentication safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains jwt-authentication?
It is published by pluginagentmarketplace in pluginagentmarketplace/custom-plugin-nodejs. It has 226 recorded installs.
More from pluginagentmarketplace/custom-plugin-nodejs
express-rest-api
pluginagentmarketplace/custom-plugin-nodejs
Build production-ready RESTful APIs with Express.js including routing, middleware, validation, and error handling for scalable backend services
mongoose-mongodb
pluginagentmarketplace/custom-plugin-nodejs
Work with MongoDB in Node.js using Mongoose ODM for schema design, CRUD operations, relationships, and advanced queries
docker-deployment
pluginagentmarketplace/custom-plugin-nodejs
Containerize and deploy Node.js applications with Docker including multi-stage builds, Docker Compose, and production optimization
jest-testing
pluginagentmarketplace/custom-plugin-nodejs
Test Node.js applications with Jest including unit tests, integration tests, mocking, code coverage, and CI/CD integration
async-patterns
pluginagentmarketplace/custom-plugin-nodejs
Master asynchronous programming in Node.js with Promises, async/await, streams, and event-driven patterns for efficient non-blocking operations
websockets
pluginagentmarketplace/custom-plugin-nodejs
Implement real-time bidirectional communication with Socket.io and ws library for chat, notifications, and live dashboards
Popular backend & apis skills
find-skills
vercel-labs/skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
entra-app-registration
microsoft/azure-skills
Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.
google-agents-cli-adk-code
google/agents-cli
This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).
embedded-captions
heygen-com/hyperframes
Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.
entra-agent-id
microsoft/azure-skills
Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).
neon
neondatabase/agent-skills
Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.