api-authentication
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Authentication
API身份验证
Implement secure authentication mechanisms for APIs using modern standards and best practices.
为API实现符合现代标准和最佳实践的安全身份验证机制。
Authentication Methods
认证方式
| Method | Use Case | Security Level |
|---|---|---|
| JWT | Stateless auth, SPAs | High |
| OAuth 2.0 | Third-party integration | High |
| API Keys | Service-to-service | Medium |
| Session | Traditional web apps | High |
| 方式 | 适用场景 | 安全级别 |
|---|---|---|
| JWT | 无状态认证、SPAs | 高 |
| OAuth 2.0 | 第三方集成 | 高 |
| API Keys | 服务间通信 | 中 |
| Session | 传统Web应用 | 高 |
JWT Implementation (Node.js)
JWT实现(Node.js)
javascript
const jwt = require('jsonwebtoken');
const generateTokens = (user) => ({
accessToken: jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
),
refreshToken: jwt.sign(
{ userId: user.id, type: 'refresh' },
process.env.REFRESH_SECRET,
{ expiresIn: '7d' }
)
});
const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;
// Validate authorization header format
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Malformed authorization header' });
}
const parts = authHeader.split(' ');
if (parts.length !== 2) {
return res.status(401).json({ error: 'Malformed authorization header' });
}
const token = parts[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
};javascript
const jwt = require('jsonwebtoken');
const generateTokens = (user) => ({
accessToken: jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
),
refreshToken: jwt.sign(
{ userId: user.id, type: 'refresh' },
process.env.REFRESH_SECRET,
{ expiresIn: '7d' }
)
});
const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;
// Validate authorization header format
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Malformed authorization header' });
}
const parts = authHeader.split(' ');
if (parts.length !== 2) {
return res.status(401).json({ error: 'Malformed authorization header' });
}
const token = parts[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
};Security Requirements
安全要求
- Always use HTTPS
- Store tokens in HttpOnly cookies (not localStorage)
- Hash passwords with bcrypt (cost factor 12+)
- Implement rate limiting on auth endpoints
- Rotate secrets regularly
- Never transmit tokens in URLs
- 始终使用HTTPS
- 将令牌存储在HttpOnly cookies中(不要存储在localStorage)
- 使用bcrypt哈希密码(成本因子12及以上)
- 在认证端点实现速率限制
- 定期轮换密钥
- 禁止在URL中传输令牌
Security Headers
安全头
javascript
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
next();
});javascript
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
next();
});Additional Implementations
更多实现
See references/python-flask.md for:
- Flask JWT with role-based access control decorators
- OAuth 2.0 Google integration with Authlib
- API key authentication with secure hashing
查看 references/python-flask.md 获取以下内容:
- 基于角色权限控制装饰器的Flask JWT实现
- 基于Authlib的OAuth 2.0谷歌集成
- 带安全哈希的API密钥认证
Common Mistakes to Avoid
需要避免的常见错误
- Storing plain-text passwords
- Using weak JWT secrets
- Ignoring token expiration
- Disabling HTTPS in production
- Logging sensitive tokens
- 存储明文密码
- 使用弱JWT密钥
- 忽略令牌过期时间
- 生产环境禁用HTTPS
- 打印敏感令牌日志