使用 JWT 的身份验证中间件
使用 JSON Web Token 为 Express 应用构建安全的身份验证,并学习如何通过自定义身份验证中间件保护路由。
使用 JWT 的身份验证中间件 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Tokens?
HTTP is stateless: the server forgets you between requests. To know who is making a request, the client sends proof of identity each time.
JSON Web Tokens (JWT) are a popular, stateless way to carry that proof without storing sessions on the server.
Anatomy of a JWT
A JWT is three Base64 sections separated by dots:
- Header: the signing algorithm
- Payload: claims like user id and role
- Signature: verifies the token was not tampered with
The payload is encoded, not encrypted — never put secrets in it.
// xxxxx.yyyyy.zzzzz
// header.payload.signatureInstalling jsonwebtoken
The jsonwebtoken package handles creating and verifying tokens.
// npm install jsonwebtoken
const jwt = require('jsonwebtoken');Signing a Token on Login
After verifying a user's credentials, call jwt.sign() with the payload, a secret, and options like expiry. Send the resulting token back to the client.
const token = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });Sending the Token
The client stores the token and sends it back on each request, usually in the Authorization header using the Bearer scheme.
// Authorization: Bearer eyJhbGci...Reading the Token in Middleware
Auth middleware extracts the token from the header. Split off the Bearer prefix to get the raw token string.
function auth(req, res, next) {
const header = req.get('Authorization') || '';
const token = header.split(' ')[1];
// verify next...
}Verifying the Token
jwt.verify() checks the signature and expiry. If valid it returns the decoded payload; if not it throws, so wrap it in try/catch.
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.user = payload;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}Complete Auth Middleware
Putting it together, this middleware rejects missing or invalid tokens and attaches the user to the request for downstream handlers.
function auth(req, res, next) {
const token = (req.get('Authorization') || '').split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}Protecting Routes
Apply the middleware to any route that requires login. Express runs it before the handler, blocking unauthenticated requests automatically.
app.get('/profile', auth, (req, res) => {
res.json({ id: req.user.userId });
});Role-Based Authorization
Authentication answers "who are you?"; authorization answers "are you allowed?". A second middleware can check req.user.role set by the auth step.
function requireAdmin(req, res, next) {
if (req.user.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden' });
}
next();
}
app.delete('/users/:id', auth, requireAdmin, handler);Security Best Practices
Keep tokens safe:
- Store the secret in an environment variable, never in code
- Use short expiry times and refresh tokens for longer sessions
- Always serve over HTTPS
- Return
401for missing/invalid auth,403for insufficient permissions
Quick Check
Test your understanding of JWT auth.
Recap
You built stateless authentication with JWT:
- Sign a token on login with
jwt.sign() - Send it via the
Authorization: Bearerheader - Verify it in custom middleware with
jwt.verify() - Attach
req.userand protect routes - Add role checks for authorization
This is the foundation of secure Express APIs.
常见问题解答
「使用 JWT 的身份验证中间件」课时是免费的吗?
是的 — 「使用 JWT 的身份验证中间件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「使用 JWT 的身份验证中间件」这节课中我会学到什么?
使用 JSON Web Token 为 Express 应用构建安全的身份验证,并学习如何通过自定义身份验证中间件保护路由。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 JWT 的身份验证中间件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 开发自定义 Express 中间件
- 全局错误处理策略
- 使用 Joi/Express-Validator 验证输入
- 使用 JWT 的身份验证中间件