简介:本文系统梳理Rest API认证的四大主流模式(HTTP Basic、Token、OAuth 2.0、JWT),结合安全规范、适用场景及实现代码,为开发者提供认证方案选型指南。
Rest API作为无状态的服务接口,其认证机制需解决三大核心问题:身份验证(Who are you?)、权限控制(What can you do?)、会话管理(How long are you valid?)。根据OWASP统计,API安全漏洞中35%源于认证机制缺陷,包括弱认证、会话固定、令牌泄露等问题。开发者需在安全性、性能、开发复杂度之间寻找平衡点。
GET /api/data HTTP/1.1Authorization: Basic base64(username:password)
客户端将用户名密码按username:password格式拼接后Base64编码,通过Authorization头传输。Spring Boot实现示例:
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.httpBasic().and().authorizeRequests().antMatchers("/api/**").authenticated();}}
/auth接口Authorization: Token xxx
// 生成Tokenconst generateToken = () => crypto.randomBytes(16).toString('hex');// 验证中间件app.use((req, res, next) => {const token = req.headers['authorization']?.split(' ')[1];if (redis.get(token)) return next();res.status(401).send('Invalid token');});
| 模式 | 适用场景 | 流程特点 |
|---|---|---|
| 授权码模式 | 第三方应用集成 | 需后端交互,安全性最高 |
| 隐式模式 | 纯前端应用 | 直接返回Token,无后端参与 |
| 密码模式 | 高度信任的客户端 | 直接传输用户名密码 |
| 客户端凭证 | 机器对机器通信 | 仅验证客户端身份 |
@Configuration@EnableAuthorizationServerpublic class AuthServerConfig extends AuthorizationServerConfigurerAdapter {@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("client1").secret("{noop}secret").authorizedGrantTypes("authorization_code", "refresh_token").scopes("read", "write").redirectUris("http://localhost:8080/callback");}}
JWT由三部分组成:
Header.Payload.Signature
示例Token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
const jwt = require('jsonwebtoken');// 生成Tokenconst token = jwt.sign({ userId: 123, role: 'admin' },'your-secret-key',{ expiresIn: '1h' });// 验证中间件app.use((req, res, next) => {try {const decoded = jwt.verify(req.headers.token, 'secret');req.user = decoded;next();} catch (err) {res.status(401).send('Invalid token');}});
Rest API认证模式的选择没有银弹,需根据业务场景、安全需求和技术栈综合决策。从简单的HTTP Basic到复杂的OAuth 2.0+JWT组合,每种方案都有其适用边界。建议开发者建立认证模式评估矩阵,从安全性、性能、开发成本、维护复杂度四个维度进行量化分析,最终选择最适合当前业务阶段的认证方案。