API 安全设计最佳实践

系列导读:本篇将深入讲解 API 安全设计的核心方法与最佳实践。


文章目录

    • 目录
    • [一、API 安全威胁](#一、API 安全威胁)
      • [1.1 常见威胁](#1.1 常见威胁)
      • [1.2 OWASP API Top 10](#1.2 OWASP API Top 10)
    • 二、认证与授权
      • [2.1 OAuth2 认证](#2.1 OAuth2 认证)
      • [2.2 JWT Token](#2.2 JWT Token)
      • [2.3 RBAC 权限控制](#2.3 RBAC 权限控制)
    • [三、API 网关安全](#三、API 网关安全)
      • [3.1 Kong 网关配置](#3.1 Kong 网关配置)
      • [3.2 限流配置](#3.2 限流配置)
    • 四、安全最佳实践
      • [4.1 输入验证](#4.1 输入验证)
      • [4.2 敏感数据保护](#4.2 敏感数据保护)
      • [4.3 安全响应头](#4.3 安全响应头)
    • 总结

目录


一、API 安全威胁

1.1 常见威胁

威胁 说明
注入攻击 SQL、命令注入
越权访问 水平/垂直越权
数据泄露 敏感信息暴露
DDoS 攻击 拒绝服务
中间人攻击 数据窃取

1.2 OWASP API Top 10

复制代码
1. 对象级别授权失效
2. 身份认证失效
3. 对象属性级别授权失效
4. 资源消耗无限制
5. 功能级别授权失效
6. 批量操作不受限
7. 注入攻击
8. 安全配置错误
9. 库组件版本过旧
10. 日志与监控不足

二、认证与授权

2.1 OAuth2 认证

java 复制代码
// OAuth2 配置
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
    
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client-app")
            .secret("{bcrypt}$2a$10$...")
            .authorizedGrantTypes("authorization_code", "refresh_token")
            .scopes("read", "write")
            .redirectUris("https://app.example.com/callback");
    }
}

2.2 JWT Token

java 复制代码
// JWT 生成
public String generateToken(User user) {
    return Jwts.builder()
        .setSubject(user.getId())
        .claim("roles", user.getRoles())
        .setIssuedAt(new Date())
        .setExpiration(new Date(System.currentTimeMillis() + 3600000))
        .signWith(SignatureAlgorithm.HS256, secretKey)
        .compact();
}

// JWT 验证
public Claims parseToken(String token) {
    return Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();
}

2.3 RBAC 权限控制

java 复制代码
// 权限注解
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Long id) {
    userService.delete(id);
}

// 动态权限
@PreAuthorize("@permissionChecker.check(#id)")
@GetMapping("/orders/{id}")
public Order getOrder(@PathVariable Long id) {
    return orderService.getById(id);
}

三、API 网关安全

3.1 Kong 网关配置

yaml 复制代码
# Kong 插件配置
_format_version: "3.0"

services:
- name: order-service
  url: http://order-service:8080
  plugins:
  - name: jwt
    config:
      secret_is_base64: false
  - name: rate-limiting
    config:
      minute: 100
      policy: local
  - name: request-size-limiting
    config:
      allowed_payload_size: 10

3.2 限流配置

java 复制代码
// 限流注解
@RateLimiter(value = 10, timeout = 1, timeUnit = TimeUnit.SECONDS)
@GetMapping("/api/orders")
public List<Order> listOrders() {
    return orderService.list();
}

四、安全最佳实践

4.1 输入验证

java 复制代码
// 参数校验
@PostMapping("/users")
public User createUser(@Valid @RequestBody UserDTO dto) {
    return userService.create(dto);
}

// DTO 校验规则
@Data
public class UserDTO {
    @NotBlank(message = "用户名不能为空")
    @Size(min = 3, max = 20, message = "用户名长度3-20")
    private String username;
    
    @Email(message = "邮箱格式不正确")
    private String email;
    
    @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
    private String phone;
}

4.2 敏感数据保护

java 复制代码
// 数据脱敏
@JsonSerialize(using = PhoneMaskSerializer.class)
private String phone;  // 138****8888

// 加密存储
@Encrypt
private String idCard;

// 日志脱敏
log.info("用户登录: phone={}", MaskUtils.maskPhone(phone));

4.3 安全响应头

java 复制代码
@Configuration
public class SecurityHeaderConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.headers()
            .contentSecurityPolicy("default-src 'self'")
            .and()
            .xssProtection()
            .and()
            .frameOptions().deny()
            .httpStrictTransportSecurity();
        return http.build();
    }
}

总结

API 安全威胁 :OWASP Top 10

认证与授权 :OAuth2、JWT、RBAC

API 网关安全 :Kong、限流

安全最佳实践:输入验证、数据保护、安全头

下篇预告身份认证与授权架构设计


作者 :刘~浪地球
系列 :安全架构(二)
更新时间:2026-04-20

相关推荐
Avan_菜菜3 小时前
FRP 内网穿透完整实战:从 HTTP 映射到 HTTPS 自签代理
运维·nginx·https
冬奇Lab1 天前
Skill 系列(02):Skill 安全风险——三类攻击面的实战测试
人工智能·安全·开源
SelectDB1 天前
Litefuse 开源并推出单进程轻量模式,25 秒就能跑起来的 Agent 可观测与评估平台
运维·后端·自动化运维
XIAOHEZIcode3 天前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
用户0328472220703 天前
如何搭建本地yum源(上)
运维
Aphasia3114 天前
VPN 与内网穿透
安全
Mr_愚人派6 天前
当"Claude"不再是 Claude:一次第三方 API 代理引发的 AI 身份伪造排查实录
人工智能·安全
大树886 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠6 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质6 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务