Generated banner for Spring Security
Generated logo for Spring Security

Spring Security

GitHubOfficialFirst committed by jduboisDistributed by GitHub

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

Configure, test and review Spring Security 6/7 in Spring Boot 3/4 apps: SecurityFilterChain lambda DSL, method security, OAuth2 resource server with JWT, OIDC login, CSRF/CORS, password encoding, headers, actuator protection, and MockMvc security tests. Use when adding or auditing authentication and authorization.
— the description by jdubois

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides structured guidance for implementing and auditing security in Spring Boot 3.x and 4.x applications. It covers the configuration of SecurityFilterChain, method-level security, OAuth2/OIDC integration, and essential web protections like CSRF, CORS, and security headers. The skill emphasizes modern lambda-based DSL configurations, proper Actuator endpoint protection, and security testing practices using MockMvc.

What it does

  • Provides configuration patterns for SecurityFilterChain and method security.
  • Guides the implementation of OAuth2 resource servers and OIDC login flows.
  • Details best practices for managing sessions, CSRF, CORS, and security headers.
  • Offers strategies for securing Actuator endpoints to prevent information leakage.
  • Includes a checklist for auditing common security mistakes in Spring applications.
  • Outlines testing approaches for verifying security constraints.

When to use it

  • When setting up authentication and authorization for a new Spring Boot application.
  • When upgrading security configurations from older Spring Security versions.
  • When auditing an existing application for security vulnerabilities or misconfigurations.
  • When implementing specific security requirements like JWT-based stateless APIs or OIDC-based browser sessions.

Advantages

  • Promotes the use of modern, type-safe lambda DSL configurations.
  • Helps prevent common security pitfalls like accidental exposure of Actuator endpoints.
  • Provides clear decision-making frameworks for choosing between session-based and stateless authentication.
  • Encourages a secure-by-default approach to application architecture.

Usage examples

“How do I configure a stateless JWT resource server in Spring Boot 3?”
The agent provides a SecurityFilterChain bean definition using .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) and sets the session management policy to STATELESS.
“What is the best way to secure Actuator endpoints in Spring Boot 3?”
The agent suggests using a dedicated SecurityFilterChain bean with @Order(1) that matches EndpointRequest.toAnyEndpoint() and restricts access to specific roles.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/github/spring-security/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip spring-security.zip -d .agents/skills

Documentation by jdubois

Spring Security

Practical guidance for Spring Security 6.x (Spring Boot 3.x) and 7.x (Spring Boot 4.x). Details per topic are in references/.

Safety rules

  • Never read, print, or commit secrets: .env, application-*.properties with credentials, client secrets, private keys, JWT signing keys. Reference them via environment variables or a secret manager.

  • Never disable security (permitAll() on everything, csrf.disable() for browser apps) just to make a test or demo pass.

First: detect the version

  1. Find the Boot version (pom.xml parent/BOM, build.gradle(.kts), libs.versions.toml) and run ./mvnw dependency:tree -Dincludes=org.springframework.security or ./gradlew dependencies --configuration runtimeClasspath to see the Spring Security version.

  2. Boot 3.x -> Security 6.x; Boot 4.x -> Security 7.x. Do not mix guidance: in 7.x, APIs deprecated in 6.x are removed (for example and() chaining, authorizeRequests, AntPathRequestMatcher/MvcRequestMatcher style matchers; use the lambda DSL and requestMatchers(...)). Check the "What's New" and migration pages on docs.spring.io/spring-security when upgrading.

  3. Identify the app type: servlet MVC (SecurityFilterChain) or WebFlux (SecurityWebFilterChain, @EnableWebFluxSecurity); browser app with sessions, or stateless API.

Core configuration

Declare a SecurityFilterChain bean. WebSecurityConfigurerAdapter no longer exists.

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health/**", "/public/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable()); // only for stateless token APIs without cookies
        return http.build();
    }
}

Rules of thumb:

Decision guide

SituationApproach
REST API called by SPA/mobile/services with bearer tokensResource server + JWT, stateless, CSRF off (no cookie auth)
Server-rendered app or SPA with same-site cookie sessionForm login or OIDC login, sessions, CSRF on
SPA using BFF patternOIDC login in the backend, session cookie to browser, CSRF token via cookie repository
Internal service-to-serviceClient credentials grant, resource server on the receiving side

Dependencies (pin through the Boot BOM, no explicit versions)

  • spring-boot-starter-security, plus spring-boot-starter-oauth2-resource-server or spring-boot-starter-oauth2-client on Boot 3.x. Boot 4.x names: spring-boot-starter-security-oauth2-resource-server / spring-boot-starter-security-oauth2-client (the old names remain as deprecated aliases).

  • Tests: add spring-security-test (test scope) on Boot 3.x; on Boot 4.x use spring-boot-starter-security-test (plus spring-boot-starter-security-oauth2-resource-server-test / -client-test when those starters are used) together with modular test starters such as spring-boot-starter-webmvc-test.

Verify

Run the app's tests plus security-specific tests (401 without credentials, 403 with insufficient role, 200 with the right one, CSRF rejection on state-changing browser requests). Confirm no endpoint was accidentally left open by listing the mappings and checking each against the filter chain.

See also (prefer over this skill for the version in use): Spring Security reference https://docs.spring.io/spring-security/reference/index.html and migration chapter https://docs.spring.io/spring-security/reference/migration/index.html.

Files

references/method-security.md

Method security

Enable with @EnableMethodSecurity on a @Configuration class (replaces @EnableGlobalMethodSecurity). @PreAuthorize, @PostAuthorize, @PreFilter, @PostFilter are on by default; @Secured and JSR-250 need securedEnabled = true / jsr250Enabled = true.

@Service
class DocumentService {

    @PreAuthorize("hasRole('ADMIN') or #owner == authentication.name")
    List<Document> findByOwner(String owner) { ... }

    @PreAuthorize("hasAuthority('SCOPE_documents.write')")
    void save(Document d) { ... }

    @PostAuthorize("returnObject.owner == authentication.name")
    Document load(Long id) { ... }
}

Guidance:

  • hasRole('ADMIN') checks authority ROLE_ADMIN; hasAuthority('SCOPE_x') checks the exact string. JWT scopes become SCOPE_ authorities by default.

  • Put annotations on service-layer methods (or controllers), never on private methods or on self-invoked calls: they rely on proxies and are bypassed.

  • Prefer a custom bean for complex rules: @PreAuthorize("@documentAuth.canEdit(#id, authentication)").

  • Meta-annotations keep rules readable: @Target(METHOD) @Retention(RUNTIME) @PreAuthorize("hasRole('ADMIN')") @interface IsAdmin {}.

  • Method security complements, not replaces, URL rules: keep a deny-by-default filter chain.

  • Test with @WithMockUser (see testing); a missing proxy shows up as a test passing with no authentication.

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

First committed by
GitHub avatar of jduboisjdubois
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/spring-security · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
jdubois

AutoGineer is not affiliated with or endorsed by jdubois or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download spring-security.zip