Communitygithub.com

springboot-security

Spring Security 最佳實務:認證/授權、驗證、CSRF、機密管理、標頭設定、速率限制與相依性安全性。適用於檢視 Spring Security 認證/授權、驗證、CSRF、機密管理、標頭設定或速率限制。

springboot-security 是什麼?

這項技能為 Java Spring Boot 服務提供了一套完整的 Spring Security 安全審查最佳實務,涵蓋認證(JWT、OAuth2、Session 基礎)、授權(方法安全、角色控制)、輸入驗證(Bean Validation)、SQL 注入防護、密碼編碼(BCrypt/Argon2)、CSRF 保護、機密管理(Vault、環境變數)、安全標頭、CORS 配置、速率限制(Bucket4j)以及相依性安全(OWASP Dependency Check / Snyk)。它支援 Claude Code、Coder 等 AI 代理開發工具,透過結構化的檢查清單和程式碼範例,幫助開發者在開發過程中自動化實施安全控管,減少人為疏失。其核心價值在於將零信任、最小權限、預設拒絕等安全原則融入程式碼審查流程,確保從設計到發布都遵循業界標準的安全配置。

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

在你喜歡的 AI 中提問

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

說明文件

Spring Boot 安全審查

在新增認證、處理輸入、建立端點或處理機密時使用。

何時啟用

  • 新增認證(JWT、OAuth2、Session 基礎)
  • 實作授權(@PreAuthorize、角色基礎存取)
  • 驗證使用者輸入(Bean Validation、自訂驗證器)
  • 配置 CORS、CSRF 或安全標頭
  • 管理機密(Vault、環境變數)
  • 新增速率限制或暴力破解防護
  • 掃描相依性中的 CVE

認證

  • 偏好無狀態 JWT 或不透明令牌搭配撤銷清單
  • 使用 httpOnly、Secure、SameSite=Strict Cookie 管理 Session
  • 使用 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();
  }
}

輸入驗證

  • 使用 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 令牌的 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,而不是每個控制器
  • 限制允許的來源——在生產環境中絕不使用 *
@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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

相關技能