mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-04-08 10:23:30 +08:00
docs(zh-CN): sync Chinese docs with latest upstream changes (#304)
* docs(zh-CN): sync Chinese docs with latest upstream changes * update --------- Co-authored-by: neo <neo.dowithless@gmail.com>
This commit is contained in:
@@ -1,12 +1,23 @@
|
||||
---
|
||||
name: springboot-security
|
||||
description: Java Spring Boot 服务中关于身份验证/授权、验证、CSRF、密钥、标头、速率限制和依赖安全的 Spring Security 最佳实践。
|
||||
description: Java Spring Boot 服务中认证/授权、验证、CSRF、密钥、标头、速率限制和依赖安全性的 Spring Security 最佳实践。
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
# Spring Boot 安全审查
|
||||
|
||||
在添加身份验证、处理输入、创建端点或处理密钥时使用。
|
||||
|
||||
## 何时激活
|
||||
|
||||
* 添加身份验证(JWT、OAuth2、基于会话)
|
||||
* 实现授权(@PreAuthorize、基于角色的访问控制)
|
||||
* 验证用户输入(Bean Validation、自定义验证器)
|
||||
* 配置 CORS、CSRF 或安全标头
|
||||
* 管理密钥(Vault、环境变量)
|
||||
* 添加速率限制或暴力破解防护
|
||||
* 扫描依赖项以查找 CVE
|
||||
|
||||
## 身份验证
|
||||
|
||||
* 优先使用无状态 JWT 或带有撤销列表的不透明令牌
|
||||
@@ -42,17 +53,88 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
* 使用 `@PreAuthorize("hasRole('ADMIN')")` 或 `@PreAuthorize("@authz.canEdit(#id)")`
|
||||
* 默认拒绝;仅公开必需的 scope
|
||||
|
||||
```java
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
public class AdminController {
|
||||
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@GetMapping("/users")
|
||||
public List<UserDto> listUsers() {
|
||||
return userService.findAll();
|
||||
}
|
||||
|
||||
@PreAuthorize("@authz.isOwner(#id, authentication)")
|
||||
@DeleteMapping("/users/{id}")
|
||||
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
|
||||
userService.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 输入验证
|
||||
|
||||
* 在控制器上使用带有 `@Valid` 的 Bean 验证
|
||||
* 在 DTO 上应用约束:`@NotBlank`、`@Email`、`@Size`、自定义验证器
|
||||
* 在渲染之前使用白名单清理任何 HTML
|
||||
|
||||
```java
|
||||
// BAD: No validation
|
||||
@PostMapping("/users")
|
||||
public User createUser(@RequestBody UserDto dto) {
|
||||
return userService.create(dto);
|
||||
}
|
||||
|
||||
// GOOD: Validated DTO
|
||||
public record CreateUserDto(
|
||||
@NotBlank @Size(max = 100) String name,
|
||||
@NotBlank @Email String email,
|
||||
@NotNull @Min(0) @Max(150) Integer age
|
||||
) {}
|
||||
|
||||
@PostMapping("/users")
|
||||
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(userService.create(dto));
|
||||
}
|
||||
```
|
||||
|
||||
## SQL 注入预防
|
||||
|
||||
* 使用 Spring Data 存储库或参数化查询
|
||||
* 对于原生查询,使用 `:param` 绑定;切勿拼接字符串
|
||||
|
||||
```java
|
||||
// BAD: String concatenation in native query
|
||||
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
|
||||
|
||||
// GOOD: Parameterized native query
|
||||
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
|
||||
List<User> findByName(@Param("name") String name);
|
||||
|
||||
// GOOD: Spring Data derived query (auto-parameterized)
|
||||
List<User> findByEmailAndActiveTrue(String email);
|
||||
```
|
||||
|
||||
## 密码编码
|
||||
|
||||
* 始终使用 BCrypt 或 Argon2 哈希密码——切勿存储明文
|
||||
* 使用 `PasswordEncoder` Bean,而非手动哈希
|
||||
|
||||
```java
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder(12); // cost factor 12
|
||||
}
|
||||
|
||||
// In service
|
||||
public User register(CreateUserDto dto) {
|
||||
String hashedPassword = passwordEncoder.encode(dto.password());
|
||||
return userRepository.save(new User(dto.email(), hashedPassword));
|
||||
}
|
||||
```
|
||||
|
||||
## CSRF 保护
|
||||
|
||||
* 对于浏览器会话应用程序,保持 CSRF 启用;在表单/头中包含令牌
|
||||
@@ -70,6 +152,25 @@ http
|
||||
* 保持 `application.yml` 不包含凭据;使用占位符
|
||||
* 定期轮换令牌和数据库凭据
|
||||
|
||||
```yaml
|
||||
# BAD: Hardcoded in application.yml
|
||||
spring:
|
||||
datasource:
|
||||
password: mySecretPassword123
|
||||
|
||||
# GOOD: Environment variable placeholder
|
||||
spring:
|
||||
datasource:
|
||||
password: ${DB_PASSWORD}
|
||||
|
||||
# GOOD: Spring Cloud Vault integration
|
||||
spring:
|
||||
cloud:
|
||||
vault:
|
||||
uri: https://vault.example.com
|
||||
token: ${VAULT_TOKEN}
|
||||
```
|
||||
|
||||
## 安全头
|
||||
|
||||
```java
|
||||
@@ -82,11 +183,63 @@ http
|
||||
.referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));
|
||||
```
|
||||
|
||||
## CORS 配置
|
||||
|
||||
* 在安全过滤器级别配置 CORS,而非按控制器配置
|
||||
* 限制允许的来源——在生产环境中切勿使用 `*`
|
||||
|
||||
```java
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(List.of("https://app.example.com"));
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
|
||||
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
|
||||
config.setAllowCredentials(true);
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/api/**", config);
|
||||
return source;
|
||||
}
|
||||
|
||||
// In SecurityFilterChain:
|
||||
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));
|
||||
```
|
||||
|
||||
## 速率限制
|
||||
|
||||
* 在昂贵的端点上应用 Bucket4j 或网关级限制
|
||||
* 记录突发流量并告警;返回 429 并提供重试提示
|
||||
|
||||
```java
|
||||
// Using Bucket4j for per-endpoint rate limiting
|
||||
@Component
|
||||
public class RateLimitFilter extends OncePerRequestFilter {
|
||||
private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
||||
|
||||
private Bucket createBucket() {
|
||||
return Bucket.builder()
|
||||
.addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1))))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
String clientIp = request.getRemoteAddr();
|
||||
Bucket bucket = buckets.computeIfAbsent(clientIp, k -> createBucket());
|
||||
|
||||
if (bucket.tryConsume(1)) {
|
||||
chain.doFilter(request, response);
|
||||
} else {
|
||||
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
|
||||
response.getWriter().write("{\"error\": \"Rate limit exceeded\"}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 依赖项安全
|
||||
|
||||
* 在 CI 中运行 OWASP Dependency Check / Snyk
|
||||
|
||||
Reference in New Issue
Block a user