TExcelTAD
Home › Spring Boot › Spring Security Basics

Spring Security Basics

Spring Security handles authentication (who are you?) and authorization (what may you do?). Adding the starter immediately locks down every endpoint; you then open up and configure exactly what you need through a SecurityFilterChain bean.

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Secure by default

With only the starter added, Boot creates one user named user with a random password printed at startup, and requires authentication for every request:

bash · try it yourself
./mvnw spring-boot:run | grep -A2 "generated security password"
Using generated security password: 3f6c1b8e-2a4d-4c71-9e0b-5d2f7a8c4e19

This generated password is for development use only. Your security configuration must be updated before running your application in production.
bash · try it yourself
curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/api/tasks
curl -s -u user:3f6c1b8e-2a4d-4c71-9e0b-5d2f7a8c4e19 -o /dev/null -w "%{http_code}\n" localhost:8080/api/tasks
401
200

How it works: a chain of filters

Every request passes through a chain of servlet filters before reaching your controller. Each filter does one job — read a Basic auth header, validate a JWT, check CSRF, decide authorization — and either passes the request on or stops it with 401/403.

Status Meaning in Spring Security
401 Unauthorized not authenticated: no or invalid credentials
403 Forbidden authenticated, but lacks the required role/authority

This plain-Java model shows the idea — authentication first, then an authorization rule per path:

java · try it yourself
import java.util.*;

record Request(String method, String path, String authorization) {}
record User(String name, String password, Set<String> roles) {}

class SecurityChain {
    private final Map<String, User> users = Map.of(
        "linh", new User("linh", "s3cret", Set.of("USER")),
        "admin", new User("admin", "adm1n", Set.of("USER", "ADMIN")));

    String handle(Request r) {
        // 1. public endpoints skip authentication
        if (r.path().startsWith("/actuator/health")) return "200 OK (public)";

        // 2. authentication: HTTP Basic "user:password"
        User user = null;
        if (r.authorization() != null) {
            String[] parts = r.authorization().split(":", 2);
            User candidate = users.get(parts[0]);
            if (candidate != null && candidate.password().equals(parts[1])) user = candidate;
        }
        if (user == null) return "401 Unauthorized";

        // 3. authorization rules
        if (r.path().startsWith("/api/admin") && !user.roles().contains("ADMIN")) return "403 Forbidden";
        if (r.method().equals("DELETE") && !user.roles().contains("ADMIN")) return "403 Forbidden";

        return "200 OK -> controller sees principal '" + user.name() + "'";
    }
}

class Main {
    public static void main(String[] args) {
        SecurityChain chain = new SecurityChain();
        List<Request> requests = List.of(
            new Request("GET", "/actuator/health", null),
            new Request("GET", "/api/tasks", null),
            new Request("GET", "/api/tasks", "linh:wrong"),
            new Request("GET", "/api/tasks", "linh:s3cret"),
            new Request("DELETE", "/api/tasks/3", "linh:s3cret"),
            new Request("DELETE", "/api/tasks/3", "admin:adm1n"),
            new Request("GET", "/api/admin/stats", "linh:s3cret"));
        for (Request r : requests) {
            System.out.printf("%-6s %-18s %-12s -> %s%n", r.method(), r.path(),
                    r.authorization() == null ? "(anonymous)" : r.authorization().split(":")[0], chain.handle(r));
        }
    }
}
GET    /actuator/health   (anonymous)  -> 200 OK (public)
GET    /api/tasks         (anonymous)  -> 401 Unauthorized
GET    /api/tasks         linh         -> 401 Unauthorized
GET    /api/tasks         linh         -> 200 OK -> controller sees principal 'linh'
DELETE /api/tasks/3       linh         -> 403 Forbidden
DELETE /api/tasks/3       admin        -> 200 OK -> controller sees principal 'admin'
GET    /api/admin/stats   linh         -> 403 Forbidden

Configuring the filter chain

The real configuration expresses the same rules with the lambda DSL:

java
@Configuration
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults())
            .csrf(csrf -> csrf.disable())                  // stateless API, no browser sessions
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .build();
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
            User.withUsername("linh").password(encoder.encode("s3cret")).roles("USER").build(),
            User.withUsername("admin").password(encoder.encode("adm1n")).roles("USER", "ADMIN").build());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();   // bcrypt by default
    }
}

Rules are evaluated top to bottom and the first match wins, so put specific matchers before anyRequest().

bash · try it yourself
curl -s -u linh:s3cret -X DELETE localhost:8080/api/tasks/3 | jq
{
  "timestamp": "2025-10-16T04:41:27.305+00:00",
  "status": 403,
  "error": "Forbidden",
  "path": "/api/tasks/3"
}

Passwords are hashed, never stored

PasswordEncoder stores a one-way bcrypt hash such as {bcrypt}$2a$10$.... The {bcrypt} prefix lets the delegating encoder support several algorithms and upgrade old hashes later. In a real application the users come from your database through a custom UserDetailsService.

Method security and the current user

java
@Service
class TaskService {
    @PreAuthorize("hasRole('ADMIN') or #ownerName == authentication.name")
    public void delete(long id, String ownerName) { ... }
}

@GetMapping("/api/me")
Map<String, Object> me(@AuthenticationPrincipal UserDetails user) {
    return Map.of("name", user.getUsername(), "roles", user.getAuthorities());
}

Tokens instead of passwords

Production APIs usually accept JWT bearer tokens issued by an identity provider (Keycloak, Auth0, Okta, Azure AD…). With spring-boot-starter-oauth2-resource-server, one property is enough to validate them:

properties
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://login.example.com/realms/tasks
java
http.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));

Tip: Disable CSRF only for stateless APIs that authenticate every request with a header (Basic or Bearer). Browser apps using session cookies need CSRF protection.

Test yourself

What happens to your endpoints right after adding spring-boot-starter-security?

  1. Nothing until you configure it
  2. All endpoints require authentication; a generated password is printed
  3. Only POST endpoints are protected
  4. The application refuses to start

An authenticated user without the ADMIN role calls an ADMIN-only endpoint. Which status is returned?

  1. 401
  2. 403
  3. 404
  4. 500

Why must specific requestMatchers come before anyRequest()?

  1. Alphabetical order is required
  2. Rules are evaluated in order and the first match wins
  3. anyRequest() must be first
  4. Order does not matter