Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SB
Spring Boot
0/10 completed
Beginner
Spring Boot setupControllers and RESTBeans and dependency injection
Intermediate
Spring Data JPAValidation and error handlingTesting Spring Boot apps
Advanced
Spring SecurityRelationships, paging and migrationsMicroservices with Spring
Pro
Production-ready Spring Boot
Tracks / Spring Boot / Advanced

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:

xml
<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:

java
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 Authorization header, 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:

java
@GetMapping("/api/orders/mine")
@Transactional(readOnly = true)
public List<OrderView> mine(@AuthenticationPrincipal UserDetails user) {
    return orders.findWithDetailsByCustomerEmail(user.getUsername()).stream()
            .map(OrderView::from)
            .toList();
}
bash
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/mine
Output
HTTP/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:

java
@GetMapping("/api/admin/stats")
public Stats stats(Principal principal) {
    return new Stats(principal.getName(), 2);
}
bash
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
Output
{"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:

java
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('ADMIN')")
public void delete(@PathVariable Long id) {
    products.deleteById(id);
}
bash
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/7
Output
HTTP/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:

properties
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.myshop.example/realms/shop
java
http.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:

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

  1. Allow GET /actuator/info without authentication.
  2. Add a support role that may call GET /api/admin/stats but not DELETE /api/products/**.
  3. Replace the in-memory users with a UserDetailsService that loads users from a JPA repository.
✎ Check your understanding

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?

← Testing Spring Boot apps