Spring Boot 安全審查 是做什麼的?
在添加身份驗證、處理輸入、建立端點或處理機密時使用。
何時啟用
- 添加身份驗證(JWT、OAuth2、基於 session)
- 實現授權(@PreAuthorize、基於角色的訪問)
- 驗證用戶輸入(Bean Validation、自定義驗證器)
- 配置 CORS、CSRF 或安全標頭
- 管理機密(Vault、環境變數)
- 添加速率限制或暴力破解保護
- 掃描依賴項中的 CVE
身份驗證
- 優先使用無狀態 JWT 或帶有撤銷清單的不透明令牌
- 對於 session,使用
httpOnly、Secure、SameSite=Strictcookie - 使用
OncePerRequestFilter或資源伺服器驗證令牌
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith("Bearer ")) {
String token = header.substring(7);
Authentication auth = jwtService.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(request, response);
}
}
授權
- 啟用方法安全性:
@EnableMethodSecurity - 使用
@PreAuthorize("hasRole('ADMIN')")或@PreAuthorize("@authz.canEdit(#id)") - 預設拒絕;僅暴露必要的範圍
@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();
}
}
輸入驗證
- 在 Controller 上使用 Bean Validation 和
@Valid - 在 DTO 上應用約束:
@NotBlank、@Email、@Size、自定義驗證器 - 在渲染前,使用白名單消毒任何 HTML
// 不良:無驗證
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
return userService.create(dto);
}
// 良好:已驗證的 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 Repository 或參數化查詢
- 對於原生查詢,使用
:param綁定;切勿拼接字串
// 不良:原生查詢中的字串拼接
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
// 良好:參數化原生查詢
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
List<User> findByName(@Param("name") String name);
// 良好:Spring Data 派生查詢(自動參數化)
List<User> findByEmailAndActiveTrue(String email);
密碼編碼
- 始終使用 BCrypt 或 Argon2 對密碼進行哈希處理 — 切勿儲存明文
- 使用
PasswordEncoderbean,而不是手動哈希
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // 成本因子 12
}
// 在 service 中
public User register(CreateUserDto dto) {
String hashedPassword = passwordEncoder.encode(dto.password());
return userRepository.save(new User(dto.email(), hashedPassword));
}
CSRF 保護
- 對於瀏覽器 session 應用程式,保持 CSRF 啟用;在表單/標頭中包含令牌
- 對於使用 Bearer token 的純 API,停用 CSRF 並依賴無狀態身份驗證
http
.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
機密管理
- 原始碼中不包含機密;從環境變數或 vault 加載
- 保持
application.yml不含憑證;使用佔位符 - 定期輪換令牌和資料庫憑證
# 不良:硬編碼在 application.yml 中
spring:
datasource:
password: mySecretPassword123
# 良好:環境變數佔位符
spring:
datasource:
password: ${DB_PASSWORD}
# 良好:Spring Cloud Vault 整合
spring:
cloud:
vault:
uri: https://vault.example.com
token: ${VAULT_TOKEN}
安全標頭
http
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'"))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
.xssProtection(Customizer.withDefaults())
.referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));
CORS 配置
- 在安全過濾器層級配置 CORS,而不是每個 Controller
- 限制允許的來源 — 在生產環境中切勿使用
*
@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;
}
// 在 SecurityFilterChain 中:
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));
速率限制
- 對昂貴的端點應用 Bucket4j 或閘道層級限制
- 記錄並警報突發流量;返回 429 狀態碼並附上重試提示
// 使用 Bucket4j 進行每個端點的速率限制
@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
- 讓 Spring Boot 和 Spring Security 保持在支援的版本
- 在已知 CVE 上使建置失敗
日誌與 PII
- 切勿記錄機密、令牌、密碼或完整的 PAN 資料
- 遮蔽敏感欄位;使用結構化 JSON 日誌
檔案上傳
- 驗證大小、內容類型和副檔名
- 儲存在 web 根目錄之外;如有必要進行掃描
發布前檢查清單
- 身份驗證令牌已正確驗證且未過期
- 每個敏感路徑都有授權防護
- 所有輸入均已驗證和消毒
- 沒有字串拼接的 SQL
- CSRF 的配置符合應用程式類型
- 機密已外部化;未提交任何機密
- 安全標頭已配置
- API 上有速率限制
- 依賴項已掃描且為最新
- 日誌中不含敏感資料
請記住:預設拒絕、驗證輸入、最小權限、安全優先配置。