springboot-security
Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.
About this skill
This skill equips AI agents with a comprehensive set of best practices for designing and implementing secure Java Spring Boot services. It details guidelines for robust authentication (e.g., stateless JWTs, secure sessions with `httpOnly`, `Secure`, `SameSite=Strict` cookies), authorization mechanisms, secure input validation, protection against CSRF attacks, secure handling of secrets, configuring HTTP headers for security, implementing rate limiting, and managing dependencies securely. The skill provides actionable advice and code patterns, such as using `OncePerRequestFilter` for token validation, to help AI agents generate or review production-ready, secure Spring Boot code, aligning with modern security standards and preventing common vulnerabilities. This makes the AI an invaluable assistant for developers aiming to build secure and compliant Java applications.
Best use case
Applying secure coding standards to new Spring Boot features, refactoring existing Spring Boot applications for improved security, conducting security reviews of Spring Boot code, or generating secure code snippets related to authentication, authorization, and data protection.
Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.
The AI agent will generate Spring Boot Java code that adheres to the specified security best practices. This includes correctly configured Spring Security classes, secure authentication flows (e.g., JWT filters), robust input validation logic, secure header configurations, and appropriate handling of sensitive information. Alternatively, the AI might provide detailed recommendations for improving the security posture of existing Spring Boot code, explaining the 'why' behind each suggestion and proposing concrete code changes.
Practical example
Example input
Generate a Spring Boot `@RestController` endpoint that requires JWT authentication, validates user input for a 'create user' operation, and incorporates security best practices for headers and CSRF.
Example output
Based on Spring Security best practices, here's an example of a secure `UserController` with JWT authentication, input validation, and considerations for headers and CSRF:
```java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
// --- DTOs for Request and Response ---
// Example: UserCreateRequest.java - Defines input structure and validation rules
class UserCreateRequest {
@NotBlank(message = "Username cannot be empty")
private String username;
@Email(message = "Email should be valid")
@NotBlank(message = "Email cannot be empty")
private String email;
@Size(min = 8, message = "Password must be at least 8 characters long")
@NotBlank(message = "Password cannot be empty")
private String password;
// Getters and Setters (omitted for brevity)
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
// Example: UserResponse.java - Defines output structure
class UserResponse {
private Long id;
private String username;
private String email;
public UserResponse(Long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
// Getters and Setters (omitted for brevity)
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
// --- Controller Example ---
@RestController
@RequestMapping("/api/users")
@Validated // Enable validation for controller methods if using path/query params
public class UserController {
// Assume UserService handles business logic, database interaction, and secure password hashing
// @Autowired
// private UserService userService;
@PostMapping
@PreAuthorize("hasRole('ADMIN')") // Example authorization: Only users with 'ADMIN' role can create users
public ResponseEntity<UserResponse> createUser(@Valid @RequestBody UserCreateRequest request) {
// Input validation is automatically applied via @Valid on the @RequestBody and annotations in UserCreateRequest.
// CRITICAL: Ensure passwords are NEVER stored in plain text. The 'userService' should hash them securely (e.g., using BCrypt).
// Dummy service call for demonstration. In a real app, this would call userService.createUser(request)
UserResponse response = new UserResponse(1L, request.getUsername(), request.getEmail());
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
// Other secure endpoints would follow similar patterns...
}
// --- Reminder: Example JWT Authentication Filter (as referenced in the skill's guidelines) ---
// This filter would be configured in your main Spring Security configuration chain
// ensuring every incoming request is authenticated if an 'Authorization: Bearer' token is present.
// @Component
// public class JwtAuthFilter extends OncePerRequestFilter {
// private final JwtService jwtService;
// private final UserDetailsService userDetailsService;
//
// public JwtAuthFilter(JwtService jwtService, UserDetailsService userDetailsService) {
// this.jwtService = jwtService;
// this.userDetailsService = userDetailsService;
// }
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
// throws ServletException, IOException {
// String header = request.getHeader("Authorization");
// // ... full implementation for validating stateless JWT from 'Authorization: Bearer <token>'
// // If the token is valid, create and set an Authentication object in SecurityContextHolder
// chain.doFilter(request, response);
// }
// }
```
**Key Security Best Practices Applied and Recommended:**
1. **Authentication (JWT):** The endpoint assumes JWT authentication is handled by a filter chain (like the `JwtAuthFilter` snippet from the skill). Tokens are expected in the `Authorization: Bearer <token>` header, which is standard for stateless REST APIs.
2. **Authorization:** `@PreAuthorize("hasRole('ADMIN')")` is used to enforce role-based access control, restricting access to specific user roles.
3. **Input Validation:** Robust input validation is implemented using Spring's `@Valid` annotation on the request body and Jakarta Bean Validation annotations (`@NotBlank`, `@Email`, `@Size`) within the `UserCreateRequest` DTO. This prevents common vulnerabilities like injection attacks and ensures data integrity.
4. **Password Handling:** Critical advice is provided to ensure that passwords are never stored in plain text. The `UserService` (or similar component) must securely hash passwords using strong, modern algorithms (e.g., BCrypt or Argon2) before storage.
5. **CSRF Protection:** For stateless REST APIs primarily using JWTs in `Authorization` headers (not cookies), CSRF is inherently less of a concern as the browser does not automatically attach the token. If tokens *were* stored in cookies, the skill's recommendation for `httpOnly`, `Secure`, and `SameSite=Strict` flags would be vital. For traditional session-based Spring applications, Spring Security's built-in CSRF protection should be enabled.
6. **Secure Headers:** While not directly in the controller, it's crucial to configure Spring Security to set robust HTTP security headers (e.g., `X-Content-Type-Options`, `X-Frame-Options`, `X-XSS-Protection`, `Content-Security-Policy`, `Strict-Transport-Security`). These headers mitigate various client-side attacks.
7. **Rate Limiting:** Although not implemented in the code snippet, a strong recommendation to implement rate limiting on sensitive endpoints (like user creation and especially authentication endpoints) to prevent brute-force attacks and abuse.
8. **Secret Management:** Reinforce the importance of externalizing and securely managing sensitive secrets (e.g., JWT signing keys, database credentials) using environment variables, configuration servers (Spring Cloud Config), or dedicated secret management solutions (Vault, Kubernetes Secrets), never hardcoding them directly in the application code.
9. **Dependency Security:** Remind the user to regularly scan dependencies for known vulnerabilities and keep them updated, as per the skill's guidelines on dependency security.When to use this skill
- When developing new Spring Boot microservices or APIs requiring robust authentication and authorization. When reviewing existing Spring Boot applications for security vulnerabilities or compliance with best practices. When implementing secure input validation or protecting against common web vulnerabilities like CSRF. When configuring secure HTTP headers or managing sensitive data and secrets within a Spring Boot context.
When not to use this skill
- When working with non-Spring Boot Java applications or other programming languages/frameworks. When the task does not involve security-related aspects of a Spring Boot application. For general code generation tasks that do not specifically require security considerations.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/springboot-security/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How springboot-security Compares
| Feature / Agent | springboot-security | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Spring Boot セキュリティレビュー
認証の追加、入力処理、エンドポイント作成、またはシークレット処理時に使用します。
## 認証
- ステートレスJWTまたは失効リスト付き不透明トークンを優先
- セッションには `httpOnly`、`Secure`、`SameSite=Strict` クッキーを使用
- `OncePerRequestFilter` またはリソースサーバーでトークンを検証
```java
@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)")` を使用
- デフォルトで拒否し、必要なスコープのみ公開
## 入力検証
- `@Valid` を使用してコントローラーでBean Validationを使用
- DTOに制約を適用: `@NotBlank`、`@Email`、`@Size`、カスタムバリデーター
- レンダリング前にホワイトリストでHTMLをサニタイズ
## SQLインジェクション防止
- Spring Dataリポジトリまたはパラメータ化クエリを使用
- ネイティブクエリには `:param` バインディングを使用し、文字列を連結しない
## CSRF保護
- ブラウザセッションアプリの場合はCSRFを有効にし、フォーム/ヘッダーにトークンを含める
- Bearerトークンを使用する純粋なAPIの場合は、CSRFを無効にしてステートレス認証に依存
```java
http
.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
```
## シークレット管理
- ソースコードにシークレットを含めない。環境変数またはvaultから読み込む
- `application.yml` を認証情報から解放し、プレースホルダーを使用
- トークンとDB認証情報を定期的にローテーション
## セキュリティヘッダー
```java
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)));
```
## レート制限
- 高コストなエンドポイントにBucket4jまたはゲートウェイレベルの制限を適用
- バーストをログに記録してアラートを送信し、リトライヒント付きで429を返す
## 依存関係のセキュリティ
- CIでOWASP Dependency Check / Snykを実行
- Spring BootとSpring Securityをサポートされているバージョンに保つ
- 既知のCVEでビルドを失敗させる
## ロギングとPII
- シークレット、トークン、パスワード、完全なPANデータをログに記録しない
- 機密フィールドを編集し、構造化JSONロギングを使用
## ファイルアップロード
- サイズ、コンテンツタイプ、拡張子を検証
- Webルート外に保存し、必要に応じてスキャン
## リリース前チェックリスト
- [ ] 認証トークンが正しく検証され、期限切れになっている
- [ ] すべての機密パスに認可ガードがある
- [ ] すべての入力が検証およびサニタイズされている
- [ ] 文字列連結されたSQLがない
- [ ] アプリケーションタイプに対してCSRF対策が正しい
- [ ] シークレットが外部化され、コミットされていない
- [ ] セキュリティヘッダーが設定されている
- [ ] APIにレート制限がある
- [ ] 依存関係がスキャンされ、最新である
- [ ] ログに機密データがない
**注意**: デフォルトで拒否し、入力を検証し、最小権限を適用し、設定によるセキュリティを優先します。Related Skills
laravel-security
Laravel security best practices for authn/authz, validation, CSRF, mass assignment, file uploads, secrets, rate limiting, and secure deployment.
springboot-verification
Verification loop for Spring Boot projects: build, static analysis, tests with coverage, security scans, and diff review before release or PR.
springboot-tdd
Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.
springboot-patterns
Spring Boot architecture patterns, REST API design, layered services, data access, caching, async processing, and logging. Use for Java Spring Boot backend work.
django-security
Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations.
workspace-surface-audit
Audit the active repo, MCP servers, plugins, connectors, env surfaces, and harness setup, then recommend the highest-value ECC-native skills, hooks, agents, and operator workflows. Use when the user wants help setting up Claude Code or understanding what capabilities are actually available in their environment.
safety-guard
Use this skill to prevent destructive operations when working on production systems or running agents autonomously.
repo-scan
Cross-stack source code asset audit — classifies every file, detects embedded third-party libraries, and delivers actionable four-level verdicts per module with interactive HTML reports.
project-flow-ops
Operate execution flow across GitHub and Linear by triaging issues and pull requests, linking active work, and keeping GitHub public-facing while Linear remains the internal execution layer. Use when the user wants backlog control, PR triage, or GitHub-to-Linear coordination.
manim-video
Build reusable Manim explainers for technical concepts, graphs, system diagrams, and product walkthroughs, then hand off to the wider ECC video stack if needed. Use when the user wants a clean animated explainer rather than a generic talking-head script.
laravel-plugin-discovery
Discover and evaluate Laravel packages via LaraPlugins.io MCP. Use when the user wants to find plugins, check package health, or assess Laravel/PHP compatibility.
design-system
Use this skill to generate or audit design systems, check visual consistency, and review PRs that touch styling.