Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install spring-security@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin spring-security v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install spring-security

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/spring-security/

Extract the ZIP to .github/skills/ in your repo. The folder name must match spring-security for Copilot to auto-discover it.

Skill Files (9)

SKILL.md 5.2 KB
---
name: spring-security
description: '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.'
---

# 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.

```java
@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:

- Rules are evaluated in order; put specific matchers first and end with `anyRequest().authenticated()` (deny by default).
- Use multiple `SecurityFilterChain` beans with `securityMatcher(...)` and `@Order` when the app mixes an API and a browser UI.
- Add `@EnableMethodSecurity` and use `@PreAuthorize`/`@PostAuthorize` on services for fine-grained rules; see [method security](references/method-security.md).
- Authentication choices: [OAuth2 resource server and JWT](references/oauth2-resource-server-jwt.md), [OIDC login and OAuth2 client](references/oidc-login-oauth2-client.md).
- Session vs stateless, CSRF, CORS, headers: [web protections](references/csrf-cors-sessions-headers.md).
- Passwords and users: [password encoding](references/password-encoding.md).
- Actuator endpoints: [actuator protection](references/actuator-protection.md) (see also the `spring-observability` skill if installed).
- Tests: [testing security](references/testing-security.md).
- Review: [common mistakes checklist](references/review-checklist.md).

## Decision guide

| Situation | Approach |
|---|---|
| REST API called by SPA/mobile/services with bearer tokens | Resource server + JWT, stateless, CSRF off (no cookie auth) |
| Server-rendered app or SPA with same-site cookie session | Form login or OIDC login, sessions, CSRF on |
| SPA using BFF pattern | OIDC login in the backend, session cookie to browser, CSRF token via cookie repository |
| Internal service-to-service | Client 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>.
references/
actuator-protection.md 2.0 KB
# Protecting Actuator endpoints

Actuator endpoints can leak configuration, environment, heap contents, and allow shutdown. Treat them as admin surface.

- Expose the minimum: `management.endpoints.web.exposure.include=health,info` (add `prometheus`/`metrics` only for the scraper).
- Use `EndpointRequest` for rules (import: Boot 3.x `org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest`; Boot 4.x `org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest`; both verified to compile):

```java
@Bean
@Order(1)
SecurityFilterChain actuator(HttpSecurity http) throws Exception {
    http.securityMatcher(EndpointRequest.toAnyEndpoint())
        .authorizeHttpRequests(a -> a
            .requestMatchers(EndpointRequest.to("health", "info")).permitAll()
            .anyRequest().hasRole("ACTUATOR_ADMIN"))
        .httpBasic(Customizer.withDefaults());
    return http.build();
}
```

- Defining any `SecurityFilterChain` makes Boot's default chain back off, and the chain above matches only Actuator requests. Always add a lower-priority catch-all chain (with your chosen authentication mechanism), otherwise every non-Actuator request matches no chain and is left unsecured:

```java
@Bean
@Order(2)
SecurityFilterChain application(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .httpBasic(Customizer.withDefaults()); // or formLogin / oauth2ResourceServer / oauth2Login
    return http.build();
}
```

- Never expose `env`, `configprops`, `heapdump`, `threaddump`, `loggers`, `shutdown`, `mappings`, `beans` publicly. `heapdump` can contain secrets and personal data.
- Consider a separate management port (`management.server.port`) not reachable from the internet.
- `management.endpoint.health.show-details=when-authorized` with `show-components` and roles configured.
- Sanitization of `env`/`configprops` values is on by default, but do not rely on it.

See the `spring-observability` skill for health probes, metrics, and tracing.
csrf-cors-sessions-headers.md 3.4 KB
# Sessions, CSRF, CORS, headers

## Session vs stateless

- Browser apps: default session-based (`IF_REQUIRED`), session fixation protection is on. Limit concurrent sessions via `sessionManagement(s -> s.maximumSessions(1))` if required. Use Spring Session (Redis/JDBC) for multi-instance deployments.
- Token APIs: `SessionCreationPolicy.STATELESS`; no `JSESSIONID`, no cookie auth.
- Cookies: `server.servlet.session.cookie.secure=true`, `http-only=true`, `same-site=lax` (or `strict`).

## CSRF

- Keep CSRF **enabled** for any app that authenticates with cookies/sessions (form login, OIDC login).
- Disable only for stateless bearer-token APIs: `csrf(csrf -> csrf.disable())`, or ignore specific paths with `csrf.ignoringRequestMatchers("/webhooks/**")` (and authenticate those another way, e.g. HMAC signature).
- SPA with cookie session: use the **complete SPA configuration for the installed Spring Security version** from the [CSRF reference](https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript-spa). With `CookieCsrfTokenRepository.withHttpOnlyFalse()`, the setup must both materialize the deferred token so the `XSRF-TOKEN` cookie is written and accept its raw value in `X-XSRF-TOKEN` while retaining BREACH protection for rendered tokens. A plain `CsrfTokenRequestAttributeHandler` alone does not load the deferred token; do not present it as a complete SPA setup.
- Alternatively, keep session-based CSRF and expose a token-fetch endpoint such as `GET /csrf` returning the resolved `CsrfToken` (including `token` and `headerName`). Permit that endpoint before login if needed and have the client fetch it on initialization and again after login/logout clears the previous token. Send the returned token in the returned header name on unsafe requests; do not substitute a raw cookie token for the BREACH-protected response token.
- Verify the token lifecycle: missing/invalid token rejects an unsafe request with 403, and fetching a fresh token allows an otherwise authorized request before and after authentication changes.
- Never allow state-changing GET requests.

## CORS

Configure CORS in Spring Security so preflight requests are handled before authorization:

```java
http.cors(Customizer.withDefaults());

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration c = new CorsConfiguration();
    c.setAllowedOrigins(List.of("https://app.example.com"));
    c.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    c.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    c.setMaxAge(3600L);
    UrlBasedCorsConfigurationSource s = new UrlBasedCorsConfigurationSource();
    s.registerCorsConfiguration("/api/**", c);
    return s;
}
```

- Never combine `allowedOrigins("*")` with `allowCredentials(true)`.
- List explicit origins, read from configuration per environment.

## Security headers

Defaults already send `X-Content-Type-Options`, `Cache-Control` for secured responses, `X-Frame-Options: DENY`, and HSTS (over HTTPS). Tighten as needed:

```java
http.headers(h -> h
    .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'; frame-ancestors 'none'"))
    .referrerPolicy(r -> r.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER))
    .httpStrictTransportSecurity(hsts -> hsts.includeSubDomains(true).maxAgeInSeconds(31536000)));
```

Do not call `headers.disable()`. Enforce HTTPS at the proxy; set `server.forward-headers-strategy` when behind one.
method-security.md 1.4 KB
# 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`.

```java
@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](testing-security.md)); a missing proxy shows up as a test passing with no authentication.
oauth2-resource-server-jwt.md 2.9 KB
# OAuth2 resource server with JWT

Dependency: `spring-boot-starter-oauth2-resource-server` (Boot 3.x) or `spring-boot-starter-security-oauth2-resource-server` (Boot 4.x; test companion `spring-boot-starter-security-oauth2-resource-server-test`).

## Minimal configuration

```yaml
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://issuer.example.com/realms/demo   # discovers JWKS, validates iss
          # or: jwk-set-uri: https://issuer.example.com/.well-known/jwks.json
          audiences: my-api                                    # validates aud (Boot 3.x+)
```

```java
http.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
```

Use `issuer-uri` whenever possible: it validates the issuer and the signature. Keys and secrets come from the identity provider or environment variables, never from the repository.

## Custom JwtDecoder

```java
@Bean
JwtDecoder jwtDecoder(OAuth2TokenValidator<Jwt> validator) {
    NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation("https://issuer.example.com/realms/demo");
    decoder.setJwtValidator(validator);
    return decoder;
}

@Bean
OAuth2TokenValidator<Jwt> validator() {
    return new DelegatingOAuth2TokenValidator<>(
        JwtValidators.createDefaultWithIssuer("https://issuer.example.com/realms/demo"),
        new JwtClaimValidator<List<String>>("aud", aud -> aud != null && aud.contains("my-api")));
}
```

Always validate expiry (default), issuer, and audience. Do not accept `alg: none` or symmetric keys unless deliberately designed.

## Mapping roles and scopes

By default `scope`/`scp` claims map to `SCOPE_*` authorities. For roles in a custom claim:

```java
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter scopes = new JwtGrantedAuthoritiesConverter();
    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
    converter.setJwtGrantedAuthoritiesConverter(jwt -> {
        Collection<GrantedAuthority> authorities = new ArrayList<>(scopes.convert(jwt));
        List<String> roles = jwt.getClaimAsStringList("roles");
        if (roles != null) roles.forEach(r -> authorities.add(new SimpleGrantedAuthority("ROLE_" + r)));
        return authorities;
    });
    return converter;
}
```

Register it: `.oauth2ResourceServer(o -> o.jwt(j -> j.jwtAuthenticationConverter(converter)))`. Provider-specific claim locations (for example Keycloak `realm_access.roles`) need explicit extraction.

## Opaque tokens

Use `.oauth2ResourceServer(o -> o.opaqueToken(Customizer.withDefaults()))` with `spring.security.oauth2.resourceserver.opaquetoken.introspection-uri`, `client-id`, and `client-secret` (from environment) when tokens are not JWTs.

## Notes

- Stateless: pair with `SessionCreationPolicy.STATELESS`.
- 401 vs 403: missing/invalid token gives 401 with `WWW-Authenticate`; valid token lacking authority gives 403.
- Short token lifetimes; never log tokens.
oidc-login-oauth2-client.md 2.0 KB
# OIDC login and OAuth2 client

Dependency: `spring-boot-starter-oauth2-client` (Boot 3.x) or `spring-boot-starter-security-oauth2-client` (Boot 4.x; test companion `spring-boot-starter-security-oauth2-client-test`).

## Login with an OIDC provider

```yaml
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: ${OIDC_CLIENT_ID}
            client-secret: ${OIDC_CLIENT_SECRET}
            scope: openid,profile,email
        provider:
          keycloak:
            issuer-uri: https://issuer.example.com/realms/demo
```

```java
http
    .authorizeHttpRequests(a -> a.anyRequest().authenticated())
    .oauth2Login(Customizer.withDefaults())
    .logout(l -> l.logoutSuccessHandler(oidcLogoutHandler));
```

- Client id/secret come from environment variables or a secret store; never hard-code or print them.
- Common providers (Google, GitHub, Facebook) need only `client-id`/`client-secret`; Okta and other OIDC providers also need the `issuer-uri`.
- Use `OidcClientInitiatedLogoutSuccessHandler` for RP-initiated logout.
- Authorization Code with PKCE is the default for public clients; do not use the implicit or password grants.

## Mapping authorities

Customize with a `GrantedAuthoritiesMapper` bean or an `OAuth2UserService`/`OidcUserService` to turn provider claims (groups, roles) into `ROLE_*` authorities.

## Calling other APIs (OAuth2 client)

- Servlet apps: configure `OAuth2AuthorizedClientManager` and use `RestClient` with an `OAuth2ClientHttpRequestInterceptor`, or `WebClient` with `ServletOAuth2AuthorizedClientExchangeFilterFunction` (`ServerOAuth2AuthorizedClientExchangeFilterFunction` is for WebFlux only).
- Service-to-service uses `authorization-grant-type: client_credentials`.
- Check the Spring Security reference for the exact `RestClient` support available in your version.

## Sessions and BFF

OIDC login produces an HTTP session; keep CSRF enabled and configure cookies (`SameSite`, `Secure`, `HttpOnly`) as described in [web protections](csrf-cors-sessions-headers.md).
password-encoding.md 0.6 KB
# Password encoding

Expose a `PasswordEncoder` bean: `PasswordEncoderFactories.createDelegatingPasswordEncoder()` (stores `{id}hash`, defaults to bcrypt, verifies older formats; `upgradeEncoding`/`UserDetailsPasswordService` migrate hashes over time).

- bcrypt truncates input at 72 bytes; consider Argon2 (needs Bouncy Castle `bcprov`) for long passphrases. Pick a cost of roughly 100-500 ms on production hardware.
- `User.withDefaultPasswordEncoder()` and `InMemoryUserDetailsManager` are for demos and tests only; back `UserDetailsService` with a database.
- Rate-limit login endpoints and use generic error messages to avoid user enumeration.
review-checklist.md 0.7 KB
# Security review checklist (common mistakes)

- [ ] Lambda DSL and `requestMatchers` only; no `WebSecurityConfigurerAdapter`, `authorizeRequests`, `antMatchers`, `and()`.
- [ ] Deny by default (`anyRequest().authenticated()`), specific matchers first, narrow `permitAll`.
- [ ] CSRF stays on for cookie-authenticated apps; CORS lists explicit origins (no `*` with credentials).
- [ ] JWT issuer, audience and expiry validated; roles/scopes mapped intentionally.
- [ ] Actuator limited and secured (no public `env`, `heapdump`, `threaddump`, `shutdown`, `loggers`).
- [ ] `@PreAuthorize` only on proxied, non-self-invoked methods; `@EnableMethodSecurity` present.
- [ ] Tests cover 401, 403, success, and CSRF for new endpoints.
testing-security.md 3.8 KB
# Testing Spring Security

Dependencies: `org.springframework.security:spring-security-test` (test scope, version managed by Boot). With Boot 4, use the modular test starters (`spring-boot-starter-webmvc-test`, `spring-boot-starter-security-test`).

`@WebMvcTest` package: Boot 3.x `org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest`; Boot 4.x `org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest`. Replace `@MockBean` with `@MockitoBean` (Spring Framework 6.2+/7).

## Slice test (stateless API configuration)

These tests use the stateless resource-server configuration (`SecurityConfig`: `csrf.disable()`, `SessionCreationPolicy.STATELESS`), so no CSRF token is needed. Mock `JwtDecoder` (`org.springframework.security.oauth2.jwt.JwtDecoder`) so the filter chain can initialize without production issuer configuration or an external identity provider. `@WithMockUser` supplies authentication for authorization assertions; it does not provide a decoder or test JWT decoding.

```java
@WebMvcTest(AccountController.class)
@Import(SecurityConfig.class)   // the slice does not pick up your config unless imported
class AccountControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean AccountService service;
    @MockitoBean JwtDecoder jwtDecoder;

    @Test void anonymousGets401() throws Exception {
        mvc.perform(get("/accounts")).andExpect(status().isUnauthorized());
    }

    @Test @WithMockUser(roles = "USER")
    void userGets403OnAdmin() throws Exception {
        mvc.perform(get("/admin/accounts")).andExpect(status().isForbidden());
    }

    @Test @WithMockUser(roles = "ADMIN")
    void adminOk() throws Exception {
        mvc.perform(get("/admin/accounts")).andExpect(status().isOk());
    }

    @Test @WithMockUser
    void postWithoutCsrfTokenIsAllowed() throws Exception {
        mvc.perform(post("/accounts")).andExpect(status().isCreated());
    }
}
```

## CSRF test (session/browser configuration)

CSRF applies whenever the browser attaches credentials automatically (session cookies, HTTP Basic, client certificates); it does not apply to explicit bearer tokens sent in headers. Test it against a separate configuration that keeps CSRF enabled (the default), never against the stateless `SecurityConfig` above:

```java
@Configuration
@EnableWebSecurity
class BrowserSecurityConfig {
    @Bean
    SecurityFilterChain browser(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
            .formLogin(Customizer.withDefaults()); // CSRF protection stays enabled
        return http.build();
    }
}

@WebMvcTest(AccountController.class)
@Import(BrowserSecurityConfig.class)   // not SecurityConfig
class AccountControllerCsrfTest {

    @Autowired MockMvc mvc;
    @MockitoBean AccountService service;

    @Test @WithMockUser
    void postNeedsCsrf() throws Exception {
        mvc.perform(post("/accounts")).andExpect(status().isForbidden());
        mvc.perform(post("/accounts").with(csrf())).andExpect(status().isCreated());
    }
}
```

## Post processors

- JWT resource server: `mvc.perform(get("/api/me").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_read"))))` or `jwt().jwt(j -> j.claim("roles", List.of("admin")))`.
- OIDC login: `.with(oidcLogin().idToken(t -> t.claim("email", "a@b.c")))`; OAuth2 login: `oauth2Login()`.
- Opaque token: `opaqueToken()`; basic auth: `httpBasic("user", "pw")`; arbitrary user: `user("u").roles("X")`.
- Method security: `@WithMockUser(roles = "ADMIN")` on service tests, or `@WithUserDetails` to load a real user.
- Full-stack tests: `@SpringBootTest @AutoConfigureMockMvc` (Boot 4 package `org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc`). With `MockMvcTester` (AssertJ), use `.with(...)` similarly.
- Test the denied paths as much as the allowed ones; failing to authenticate is the most important behavior.

License (MIT)

View full license text
MIT License

Copyright GitHub, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.