使用 JWT 实现无状态身份验证
使用 JSON Web Token(JWT)实现无状态身份验证,并安全地管理用户会话。
使用 JWT 实现无状态身份验证 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 3 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 6 节课。
本课时的部分内容尚未翻译,以英文显示。
What is JWT?
In this lesson, we'll dive into JSON Web Tokens (JWTs). They are a compact, URL-safe means of representing claims to be transferred between two parties.
JWTs are crucial for stateless authentication. This means the server doesn't need to store session information. Instead, all necessary user data is embedded directly within the token itself.
JWT Structure: Three Parts
A JWT is made of three distinct parts, separated by dots (.):
- Header: Information about the token itself.
- Payload: The actual data (claims) you want to transmit.
- Signature: Used to verify the token hasn't been tampered with.
It looks like this: xxxxx.yyyyy.zzzzz
The Header & Payload Deep Dive
The Header usually contains two parts:
alg: The algorithm used for signing (e.g., HMAC SHA256 or RSA).typ: The type of token, which is usually 'JWT'.
The Payload contains the 'claims' – statements about an entity (typically, the user) and additional data. Common claims include:
sub(subject): The user ID.iss(issuer): Who issued the token.exp(expiration time): When the token expires.
The Signature Explained
The Signature is what makes JWTs secure. It's created by taking the encoded Header, the encoded Payload, a secret key, and the algorithm specified in the header, then signing them.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )
If someone tries to alter the header or payload, the signature verification will fail, indicating the token is invalid or tampered with.
JWT Workflow Overview
Here's how JWTs typically work in an authentication flow:
- User logs in with credentials.
- Server verifies credentials and creates a JWT.
- Server sends the JWT back to the client.
- Client stores the JWT (e.g., in local storage or a cookie).
- For subsequent requests, the client sends the JWT (usually in the
Authorizationheader). - Server verifies the JWT's signature and expiration before processing the request.
Creating a JWT in Node.js
We'll use the popular jsonwebtoken library. First, install it with npm install jsonwebtoken.
This example shows how to sign (create) a new JWT with a payload and an expiration time. Remember to keep your secretKey very secure!
const jwt = require('jsonwebtoken');
const payload = {
userId: 'user123',
username: 'coddykit'
};
// A strong, secret key. Keep this secure in a .env file!
const secretKey = 'your_super_secret_key_12345';
const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
console.log('Generated JWT:');
console.log(token);Validating a JWT in Node.js
Once you receive a JWT from the client, your server needs to verify its authenticity. The jwt.verify() method checks the signature and expiration.
If the token is valid, it returns the decoded payload. If not, it throws an error (e.g., TokenExpiredError or JsonWebTokenError).
const jwt = require('jsonwebtoken');
// Replace with a valid token generated from the previous step
const tokenToVerify = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyMTIzIiwidXNlcm5hbWUiOiJjb2RkeWtpdCIsImlhdCI6MTY3ODg4NjQwMCwiZXhwIjoxNjc4ODkwMDAwfQ.SOME_RANDOM_SIGNATURE';
const secretKey = 'your_super_secret_key_12345';
try {
const decoded = jwt.verify(tokenToVerify, secretKey);
console.log('Token is valid!');
console.log('Decoded Payload:', decoded);
} catch (err) {
console.log('Token verification failed:');
console.log(err.message);
}Storing JWTs Securely
Where you store JWTs on the client-side is critical for security:
- Local Storage / Session Storage: Easy to use, but vulnerable to Cross-Site Scripting (XSS) attacks if malicious JavaScript can access it.
- HttpOnly Cookies: More secure against XSS because JavaScript cannot access them. However, they are vulnerable to Cross-Site Request Forgery (CSRF) if not properly protected.
Often, a combination of strategies or careful CSRF token implementation is used.
Access vs. Refresh Tokens
For enhanced security, many applications use two types of tokens:
- Access Token: Short-lived (e.g., 15 minutes to 1 hour), used for direct API calls. If stolen, its utility is limited.
- Refresh Token: Long-lived, stored securely (e.g., HttpOnly cookie). Used to obtain a new access token once the current one expires, without requiring the user to log in again.
This pattern minimizes the risk of long-lived access tokens being compromised.
JWT Component Check
Let's quickly test your understanding of JWTs!
JWTs in Summary
You've successfully learned about JSON Web Tokens! We covered:
- What JWTs are and their role in stateless authentication.
- The three parts: Header, Payload, and Signature.
- How to create and verify JWTs using Node.js.
- Important considerations for client-side storage and the use of refresh tokens.
JWTs are a powerful tool for building secure and scalable authentication systems in your Node.js applications!
常见问题解答
「使用 JWT 实现无状态身份验证」课时是免费的吗?
是的 — 「使用 JWT 实现无状态身份验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 6 节课。
「使用 JWT 实现无状态身份验证」这节课中我会学到什么?
使用 JSON Web Token(JWT)实现无状态身份验证,并安全地管理用户会话。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 6 节。
「使用 JWT 实现无状态身份验证」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 用户注册与登录
- JWT 令牌生成与验证
- 使用 JWT 实现无状态身份验证
- 集成 OAuth2 密码流程
- 基于角色的访问控制
- 基于角色的访问控制(RBAC)