To secure a Spring Boot application, add spring-boot-starter-security, declare a SecurityFilterChain bean that says which requests need authentication and which roles may call them, and register a PasswordEncoder plus a UserDetailsService. For stateless APIs, validate JWT bearer tokens with the built-in OAuth2 resource server support instead of writing your own filter.
Everything below targets Spring Boot 3.x and later with Spring Security 6 and later. WebSecurityConfigurerAdapter was removed in Spring Security 6, so older tutorials that extend it no longer compile.
As soon as spring-boot-starter-security is on the classpath, Boot auto-configures a filter chain that requires authentication for every request, enables form login and HTTP Basic, turns on CSRF protection, and creates a single user account with a random password printed at startup. That default is only a safety net. A real application replaces it with its own configuration.
The core concepts you will configure are:
| Concept | What it answers | Main type |
|---|---|---|
| Authentication | Who is calling? | AuthenticationManager, UserDetailsService |
| Authorization | What may they do? | authorizeHttpRequests, method security |
| Password storage | How are secrets kept? | PasswordEncoder |
| CSRF and CORS | Which browser requests are trusted? | csrf(), cors() configuration |
Since Spring Security 5.7 you configure security by publishing one or more SecurityFilterChain beans and using the lambda DSL. Rules are evaluated top to bottom and the first match wins, so put specific matchers before general ones and finish with anyRequest().
hasRole("ADMIN") checks for the authority ROLE_ADMIN, because Spring adds the ROLE_ prefix for you. If you store authorities such as orders:read, use hasAuthority("orders:read") instead.
Never store plain-text or fast-hash (MD5, SHA-1) passwords. Publish a PasswordEncoder and let Spring Security verify credentials through a UserDetailsService. PasswordEncoderFactories.createDelegatingPasswordEncoder() stores the algorithm id with each hash, so you can migrate algorithms later. It uses bcrypt by default.
Here UserRepository is your own Spring Data repository. When a user registers, call passwordEncoder.encode(rawPassword) and save only the result.
For REST APIs consumed by SPAs, mobile apps or other services, use bearer tokens. The simplest production-ready approach is to treat your app as an OAuth2 resource server. An identity provider such as Keycloak, Auth0, Okta or Spring Authorization Server issues the tokens, and your app only validates them.
Boot reads the issuer's metadata, downloads the signing keys, and verifies signature, expiry and issuer on every request. Scopes in the token become authorities prefixed with SCOPE_. Disabling CSRF is acceptable here only because the API does not rely on cookies for authentication.
If you must issue tokens yourself, use a maintained library such as Nimbus JOSE+JWT (already pulled in by the resource server starter) with asymmetric keys, short expiry times and refresh tokens. Do not hard-code secrets or use the unmaintained jjwt 0.9.x line shown in many old tutorials.
URL rules are coarse. Use method security to protect service-layer logic where the decision depends on the data.
@EnableMethodSecurity replaces the older @EnableGlobalMethodSecurity, and @PreAuthorize and @PostAuthorize are enabled by default with it.
CookieCsrfTokenRepository.withHttpOnlyFalse().CorsConfigurationSource bean and http.cors(Customizer.withDefaults()). List exact origins, not *, when credentials are allowed.X-Content-Type-Options, Cache-Control, X-Frame-Options). Add a Content-Security-Policy through http.headers(...) if you serve HTML.server.servlet.session.cookie.secure=true and same-site settings for session cookies.Add spring-security-test and verify both the allowed and the denied path.
No. It was deprecated in Spring Security 5.7 and removed in 6.0. Declare a SecurityFilterChain bean instead.
Only for stateless APIs that authenticate with an Authorization header and never with cookies. Browsers attach cookies automatically, so cookie-authenticated apps must keep CSRF protection.
Prefer an in-memory variable or an HttpOnly, Secure, SameSite cookie. Avoid localStorage because any XSS bug can read it.
A role is an authority with the ROLE_ prefix. hasRole("ADMIN") and hasAuthority("ROLE_ADMIN") are equivalent.
Add the starter, publish a SecurityFilterChain, hash passwords with a delegating PasswordEncoder, and validate JWTs through the OAuth2 resource server instead of custom filters. Enforce finer rules with @PreAuthorize, keep CSRF on for cookie-based apps, configure CORS explicitly, and cover the rules with spring-security-test.