Communitygithub.com

Spring Boot 安全審查

在 Java Spring Boot 服務中,針對身份驗證/授權、驗證、CSRF、機密、標頭、速率限制和依賴安全實施 Spring Security 最佳實踐。在審查 Spring Security 身份驗證/授權、驗證、CSRF、機密、標頭或速率限制時使用。

Spring Boot 安全審查 是什麼?

此技能為開發者和 AI 代理提供了一套全面的 Spring Security 最佳實踐,涵蓋 Java Spring Boot 服務的認證 (authentication)、授權 (authorization)、輸入驗證、CSRF 保護、機密管理、安全標頭配置、CORS 設定、速率限制和依賴安全性。它特別適合在添加身份驗證(如 JWT、OAuth2、會話)、實現基於角色的訪問控制(如 @PreAuthorize)、處理用戶輸入、管理機密或添加速率限制時使用。該技能支援 Claude Code、Cursor、Codex 等平台,並透過詳細的 Markdown 文檔提供可操作的指南、程式碼範例和清單,幫助開發者以安全優先的方式構建和審查 Spring Boot 應用程式。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/springboot-security

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Spring Boot 安全審查 是做什麼的?

在添加身份驗證、處理輸入、建立端點或處理機密時使用。

何時啟用

  • 添加身份驗證(JWT、OAuth2、基於 session)
  • 實現授權(@PreAuthorize、基於角色的訪問)
  • 驗證用戶輸入(Bean Validation、自定義驗證器)
  • 配置 CORS、CSRF 或安全標頭
  • 管理機密(Vault、環境變數)
  • 添加速率限制或暴力破解保護
  • 掃描依賴項中的 CVE

身份驗證

  • 優先使用無狀態 JWT 或帶有撤銷清單的不透明令牌
  • 對於 session,使用 httpOnly、Secure、SameSite=Strict cookie
  • 使用 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 對密碼進行哈希處理 — 切勿儲存明文
  • 使用 PasswordEncoder bean,而不是手動哈希
@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 上有速率限制
  • 依賴項已掃描且為最新
  • 日誌中不含敏感資料

請記住:預設拒絕、驗證輸入、最小權限、安全優先配置。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能