Communitygithub.com

springboot-security

Spring Securityのベストプラクティスを活用し、認証・認可、入力検証、CSRF、シークレット管理、セキュリティヘッダー、レート制限、依存関係のセキュリティをJava Spring Bootサービスで実装するためのスキル。Spring Securityの認証・認可、入力検証、CSRF、シークレット、ヘッダー、レート制限のレビュー時に使用します。

springboot-security とは?

このスキルは、Spring Bootアプリケーションにおいて、Spring Securityを使った包括的なセキュリティ対策を実装・レビューするためのガイドです。認証(JWT、OAuth2、セッションベース)や認可(@PreAuthorize、ロールベース)の設定方法から、Bean Validationによる入力検証、CSRF保護の適切な構成、シークレットの外部管理(環境変数やVault)、セキュリティヘッダーの設定、CORS構成、Bucket4jを用いたレート制限、依存関係の脆弱性スキャンまでをカバーします。コード例はSpring Boot 3.xとSpring Security 6.xを想定しており、実際のフィルタ実装やセキュリティ設定のスニペットが豊富に含まれています。特に、「デフォルトで拒否」「最小権限の原則」「設定によるセキュリティ」を重視した実装を推奨しており、リリース前のチェックリストも提供するため、セキュリティレビューの効率化に役立ちます。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Spring Boot セキュリティレビュー

認証の追加、入力の処理、エンドポイントの作成、またはシークレットの取り扱いを行う際に使用します。

アクティブ化のタイミング

  • 認証の追加(JWT、OAuth2、セッションベース)
  • 認可の実装(@PreAuthorize、ロールベースアクセス)
  • ユーザー入力の検証(Bean Validation、カスタムバリデータ)
  • CORS、CSRF、またはセキュリティヘッダーの設定
  • シークレットの管理(Vault、環境変数)
  • レート制限またはブルートフォース対策の追加
  • 依存関係のCVEスキャン

認証

  • ステートレスなJWTまたは失効リスト付きの不透明トークンを優先する
  • セッションにはhttpOnly、Secure、SameSite=Strictクッキーを使用する
  • 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();
  }
}

入力検証

  • コントローラーで@Validアノテーションを使用してBean Validationを適用する
  • 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リポジトリまたはパラメータ化クエリを使用する
  • ネイティブクエリでは: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
}

// サービス内
public User register(CreateUserDto dto) {
  String hashedPassword = passwordEncoder.encode(dto.password());
  return userRepository.save(new User(dto.email(), hashedPassword));
}

CSRF保護

  • ブラウザセッションアプリではCSRFを有効にし、フォーム/ヘッダーにトークンを含める
  • Bearerトークンを使用する純粋なAPIではCSRFを無効にし、ステートレス認証に依存する
http
  .csrf(csrf -> csrf.disable())
  .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

シークレット管理

  • ソースコード内にシークレットを置かない;環境変数またはVaultから読み込む
  • application.ymlに資格情報をハードコードせず、プレースホルダーを使用する
  • トークンとDB資格情報を定期的にローテーションする
# 悪い例: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.

関連スキル