🚀 现代安全指南(适用于 Java 开发者)
发布: (2025年12月3日 GMT+8 01:48)
4 min read
原文: Dev.to
Source: Dev.to
零信任规则 – 验证 用户是谁,验证 他们能访问什么,并且即使在 VPC 内也不要隐式信任任何东西。
核心流程
客户端 → API 网关 → 授权服务器 → 资源服务器
零信任规则
- 验证用户是谁。
- 验证他们能访问什么。
- 不隐式信任 — 即使在 VPC 内也是如此。
- 令牌应始终是短生命周期的。
JWT — 使用非对称密钥 (RS256)
密钥策略
- 私钥: 仅保存在授权服务器中。
- 公钥: 共享给网关和微服务用于验证。
步骤 1:生成 RSA 密钥
openssl genrsa -out private.pem 4096
openssl rsa -in private.pem -pubout -out public.pem
步骤 2:Spring Boot JWT 验证(公钥)
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth -> oauth
.jwt(jwt -> jwt.publicKey(publicKey()))
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
@Bean
public RSAPublicKey publicKey() throws Exception {
String key = Files.readString(Path.of("public.pem"))
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
byte[] decoded = Base64.getDecoder().decode(key);
return (RSAPublicKey) KeyFactory
.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(decoded));
}
防御清单 – 安全 HTTP 头
- Content‑Security‑Policy (CSP): 阻止恶意 JS 注入(防止大多数 XSS)。
- Strict‑Transport‑Security (HSTS): 强制使用 HTTPS,防止 SSL 降级。
- X‑Frame‑Options: 禁用框架嵌入,防止点击劫持。
- X‑Content‑Type‑Options: 阻止 MIME 嗅探。
安全头配置(Spring Security)
http.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'; script-src 'self'")
)
.xssProtection(xss -> xss.block(true))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::deny)
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
)
.contentTypeOptions(Customizer.withDefaults())
);
CSRF 设置
- 使用 JWT 放在请求头时: 禁用 CSRF(令牌已经提供了保护)。
http.csrf(csrf -> csrf.disable());
- 使用基于 Cookie 的认证时: 启用 CSRF 保护。
输入验证与清理
// Example using Google's JSON Sanitizer (or similar)
String sanitized = JsonSanitizer.sanitize(userInput);
// Log sanitized data only
log.info("User input: {}", sanitized);
// Simple length check
if (userInput.length() > 200) {
throw new BadRequestException();
}
API 网关职责
流程: 客户端 → WAF → 负载均衡器 → API 网关 → 微服务
- 集中式认证
- JWT 验证
- 限流 & IP 黑名单
- 路由隔离
Spring Cloud Gateway Token Relay 示例
spring:
cloud:
gateway:
routes:
- id: secure-service
uri: http://localhost:8082
predicates:
- Path=/secure/**
filters:
- RemoveRequestHeader=Cookie
- TokenRelay
无状态架构 – 使用 JWT 时不需要会话粘性。
Client
|
Load Balancer
↓
Microservice A ↔ Microservice B
Actuator 暴露
避免泄露完整系统元数据。显式配置暴露范围:
management.endpoints.web.exposure.include=health,info
management.endpoints.web.exposure.exclude=env,beans
密码编码
永远不要自行实现加密。使用 BCrypt,它故意慢以抵御暴力破解。
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
企业控制清单(分层安全)
| 层级 | 关注点 |
|---|---|
| 1 – 周边 | WAF、DDoS 缓解 |
| 2 – 网络 | 零信任、TLS 1.3 |
| 3 – 网关 | 认证、限流 |
| 4 – 应用 | OAuth2、JWT RS256 |
| 5 – 头部 | CSP、HSTS、X‑Frame‑Options |
| 6 – 代码 | 输入验证 |
| 7 – 密钥 | Vault / AWS Secrets Manager |
| 8 – 监控 | SIEM、审计日志 |
架构蓝图
📱 Client
↓ (TLS 1.3)
🌐 API Gateway (JWT validation, throttling)
↓
🔐 Microservices (RBAC + scopes)
↓
🗄 Encrypted Database (least‑privilege access)
要点
大多数项目只保护登录页面。企业级系统需要在 每一层 都进行防护。实现本文所列实践的一半,就已经领先于大多数开发者。 🚀