spring-security
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.
- License 许可
- MIT
- 最近更新
- 2026-11-15
- Stars
- ★ 4.1w
- Forks
- 5.4k
01 前言 Front Matter
- 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.
02 资源文件 8
- 参考文档references/actuator-protection.md2.0 KB
- 参考文档references/csrf-cors-sessions-headers.md3.4 KB
- 参考文档references/method-security.md1.4 KB
- 参考文档references/oauth2-resource-server-jwt.md2.9 KB
- 参考文档references/oidc-login-oauth2-client.md2.0 KB
- 参考文档references/password-encoding.md650 B
- 参考文档references/review-checklist.md729 B
- 参考文档references/testing-security.md3.8 KB
03 SKILL.md 正文
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-*.propertieswith 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
- Find the Boot version (
pom.xmlparent/BOM,build.gradle(.kts),libs.versions.toml) and run./mvnw dependency:tree -Dincludes=org.springframework.securityor./gradlew dependencies --configuration runtimeClasspathto see the Spring Security version. - 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/MvcRequestMatcherstyle matchers; use the lambda DSL andrequestMatchers(...)). Check the "What's New" and migration pages on docs.spring.io/spring-security when upgrading. - 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:
- Rules are evaluated in order; put specific matchers first and end with
anyRequest().authenticated()(deny by default). - Use multiple
SecurityFilterChainbeans withsecurityMatcher(...)and@Orderwhen the app mixes an API and a browser UI. - Add
@EnableMethodSecurityand use@PreAuthorize/@PostAuthorizeon services for fine-grained rules; see method security. - Authentication choices: OAuth2 resource server and JWT, OIDC login and OAuth2 client.
- Session vs stateless, CSRF, CORS, headers: web protections.
- Passwords and users: password encoding.
- Actuator endpoints: actuator protection (see also the
spring-observabilityskill if installed). - Tests: testing security.
- Review: common mistakes checklist.
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, plusspring-boot-starter-oauth2-resource-serverorspring-boot-starter-oauth2-clienton 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 usespring-boot-starter-security-test(plusspring-boot-starter-security-oauth2-resource-server-test/-client-testwhen those starters are used) together with modular test starters such asspring-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.
04 同仓库更多 Skills
sap-cloud-integration
SAP Cloud Integration (CPI, part of SAP Integration Suite) runtime-specific guidance for building and troubleshooting iFlows. Use when writing or reviewing CPI Groovy scripts, choosing headers vs. exchange properties, designing exception subprocesses, JMS retry, idempotency or data store patterns, or diagnosing adapter errors (SFTP, HTTP/OAuth, SOAP, IDoc, OData, AS2, Cloud Connector) from Message Processing Log (MPL) text. Not for SAP PI/PO, ABAP development, or generic Java/Groovy outside CPI.
on-device-delegate
Saves cloud-model context by briefing one bounded, read-heavy sub-task (more than about 25 KB of prose, or many files that no single command can answer) to the local-coding plugin's on-device worker, which runs on the local MAI Code 1.1 Flash model. Use for log and test triage, summarizing many files, or extracting facts from large inputs. When the user names this skill, call the skill tool in the same response as your first other tool call, never as a separate step.
scout-issue
Use when a developer wants to find the best GitHub issues to contribute to in a repository. Invoke with /scout-issue or ask to find good first issues, beginner-friendly issues, or open source work. Asks about experience level, technical skills, time, and contribution type, then searches GitHub issues, scores them, and presents ranked recommendations with match analysis.
supabase-rls-policies
Write, review, and test Supabase Row Level Security (RLS) policies so that one user cannot read or change another user's rows. Use when creating or changing tables, policies, views, or security definer functions in a Supabase project, when reviewing a migration that touches RLS, or when asked to prove user isolation with pgTAP tests that sign in as two users.
skill-distribution-audit
Audit a skill collection before release or investigate installer omissions, archived/template leakage, duplicate identities, and manifest drift. Reconcile the intended public source set, distribution manifest, and actual discovery output for a specified consumer version. Includes a deterministic set-comparison helper.
logicapps-custom-code-net10-migration
Migrate Azure Logic Apps Standard local-function custom-code projects from .NET 8 to .NET 10. Use for legacy Logic Apps custom-code workspace upgrades, project/package configuration, custom-worker settings, publication, and integrated VS Code debugging. Not for ordinary .NET applications, standalone Azure Functions, Consumption workflows, or cloud deployment.