Spring Security
Spring Security is the standard way to secure Spring applications: authentication (passwords, tokens, OAuth2 and OpenID Connect, passkeys), authorization (URL rules, method rules), password hashing, CSRF protection and security headers. It's powerful, and secure by default.
Secure by default
Add the starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>With nothing else configured, every endpoint requires authentication, a generated password is printed at startup for a user called user, a login form and HTTP Basic are enabled, and security headers are added to every response. You then configure which rules you actually want.
The security filter chain
Requests pass through a chain of servlet filters before reaching your controllers. You define the rules with a SecurityFilterChain bean. Here's a stateless API with public product browsing, an admin area, and HTTP Basic authentication:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableMethodSecurity // enables @PreAuthorize
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
.requestMatchers("/actuator/health").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.disable()) // a stateless API using Authorization headers, not cookies
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder(); // bcrypt, with an {id} prefix
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
return new InMemoryUserDetailsManager(
User.withUsername("asha@example.com").password(encoder.encode("asha-pass-123")).roles("CUSTOMER").build(),
User.withUsername("admin@example.com").password(encoder.encode("admin-pass-456")).roles("ADMIN").build());
}
}- Rules are checked in order; the first match wins, so put specific rules before general ones, and finish with
anyRequest(). - Deny by default:
anyRequest().authenticated()(or.denyAll()) means a forgotten endpoint is protected, not exposed. - CSRF protection matters when browsers authenticate automatically with cookies. This API is stateless and uses the
Authorizationheader, so it's disabled here; keep it enabled for cookie-based web apps. - The delegating password encoder stores hashes like
{bcrypt}$2a$10$…, so you can move to a stronger algorithm later without breaking existing passwords.
In a real app, UserDetailsService loads users from your database (a JPA repository), and passwords are hashed when users register.
Trying the rules
An endpoint that returns the logged-in user's own orders:
@GetMapping("/api/orders/mine")
@Transactional(readOnly = true)
public List<OrderView> mine(@AuthenticationPrincipal UserDetails user) {
return orders.findWithDetailsByCustomerEmail(user.getUsername()).stream()
.map(OrderView::from)
.toList();
}curl -i localhost:8080/api/orders/mine
curl -i -u asha@example.com:wrong localhost:8080/api/orders/mine
curl -u asha@example.com:asha-pass-123 localhost:8080/api/orders/mineHTTP/1.1 401
HTTP/1.1 401
[{"id":1,"customer":"Asha","status":"PAID","items":[{"product":"Mug","quantity":2,"price":8.99},{"product":"Teapot","quantity":1,"price":34.50}],"total":52.48},{"id":2,"customer":"Asha","status":"SHIPPED","items":[{"product":"Laptop","quantity":1,"price":899.00}],"total":899.00}]The user identity comes from authentication, never from a request parameter, so Asha can only ever see her own orders.
Role rules on URLs:
@GetMapping("/api/admin/stats")
public Stats stats(Principal principal) {
return new Stats(principal.getName(), 2);
}curl -u asha@example.com:asha-pass-123 localhost:8080/api/admin/stats
curl -u admin@example.com:admin-pass-456 localhost:8080/api/admin/stats{"timestamp":"2026-11-20T17:27:59.495Z","status":403,"error":"Forbidden","path":"/api/admin/stats"}
{"requestedBy":"admin@example.com","openOrders":2}401 for "who are you?", 403 for "you're not allowed", exactly as HTTP intends.
Method security
Some rules belong next to the code rather than in URL patterns. With @EnableMethodSecurity, annotate methods:
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('ADMIN')")
public void delete(@PathVariable Long id) {
products.deleteById(id);
}curl -i -u asha@example.com:asha-pass-123 -X DELETE localhost:8080/api/products/7
curl -i -u admin@example.com:admin-pass-456 -X DELETE localhost:8080/api/products/7HTTP/1.1 403 HTTP/1.1 200
@PreAuthorize takes expressions, so it can check ownership too: @PreAuthorize("#email == authentication.name"), or call a bean: @PreAuthorize("@orderSecurity.isOwner(#orderId, authentication)").
Token-based APIs: OAuth2 resource server
Production APIs usually accept JWT access tokens issued by an identity provider (Keycloak, Auth0, Okta, Microsoft Entra ID, Cognito) instead of passwords. Add spring-boot-starter-oauth2-resource-server and point it at the provider:
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.myshop.example/realms/shophttp.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));Spring downloads the provider's public keys, then checks every token's signature, issuer and expiry. Scopes in the token become authorities (SCOPE_orders.read) you can use in rules. For "Sign in with…" in a server-rendered web app, use spring-boot-starter-oauth2-client and .oauth2Login().
Testing secured endpoints
Add spring-boot-starter-security-test and simulate users in tests:
@Test
@WithMockUser(roles = "ADMIN")
void adminCanDelete() {
assertThat(mvc.delete().uri("/api/products/7")).hasStatusOk();
}
@Test
@WithMockUser(roles = "CUSTOMER")
void customerCannotDelete() {
assertThat(mvc.delete().uri("/api/products/7")).hasStatus(403);
}
@Test
void anonymousCannotSeeOrders() {
assertThat(mvc.get().uri("/api/orders/mine")).hasStatus(401);
}Write the "forbidden" tests as carefully as the "allowed" ones: they're what proves your security works.
Practice
- Allow
GET /actuator/infowithout authentication. - Add a
supportrole that may callGET /api/admin/statsbut notDELETE /api/products/**. - Replace the in-memory users with a
UserDetailsServicethat loads users from a JPA repository.
1.What happens when you add spring-boot-starter-security and configure nothing?
2.Why is anyRequest().authenticated() placed last?
3.When is it reasonable to disable CSRF protection?