Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 66 ยท Security

Spring Security Fundamentals

Learn what Spring Security does by default in Spring Boot, how to write a SecurityFilterChain, store passwords safely, and protect methods with roles.

Add one dependency to a Spring Boot project and every endpoint in it is locked. That sudden lockout is Spring Security doing its job: it assumes nothing should be reachable until you say so. Security is the one part of an application where a framework with strong defaults is worth far more than clever home-made code. Authentication, session handling, password storage and header protection are easy to get subtly wrong, and Spring Security has been tested against attacks for twenty years.

This lesson explains the pieces in the order you meet them: what the default configuration does, how a request travels through a chain of filters, how you describe your own rules with a SecurityFilterChain, how users and passwords are stored, and how to protect individual methods. Security has more topics than one lesson holds, so the next ones cover token-based APIs and web hardening; for a framework tour from the Spring side, see Spring Security.

Real Spring Security does not run on this site, so its code is read-only. The runnable stand-ins are a small filter chain that authenticates with HTTP Basic and authorizes by path and role, and a password encoder built on the JDK's PBKDF2 that behaves like Spring's delegating encoder.

Two different questions

Authentication Who are you?
Authorization What may you do?

Failing the first is a 401. Failing the second is a 403.

1 / 2

The default behavior

Add the starter:

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

Start the application and look at the log. You will find a line like this:

TEXT
Using generated security password: 8e557245-73e2-4286-969b-8fa7a4b4b5a5

This generated password is for development use only. Your security configuration must be updated before running your application in production.

With no code at all, Boot has configured the following: every request requires authentication; browsers get a generated login form at /login, and API clients can use HTTP Basic (an Authorization: Basic ... header); there is one user, named user, with that random password; sessions are kept with a cookie; CSRF protection rejects state-changing requests without a token; and standard security headers are added. For quick experiments you can fix the credentials:

YAML
spring:
  security:
    user:
      name: dev
      password: dev-only-secret
      roles: USER

Never ship credentials like that. They exist so a demo works in the first minute.

Requests travel through a filter chain

Spring Security is a set of servlet filters. They run before any controller, in a fixed order, and each filter either passes the request on or stops it with a response. Roughly: one filter restores the security context for the session, others handle logout and the CSRF check, one reads credentials (the login form, or a Basic header), and the last one, the authorization filter, decides whether the authenticated user may reach the requested URL.

flowchart LR
    R["Request"] --> F1["CSRF and<br/>header filters"]
    F1 --> F2["Authentication<br/>filter"]
    F2 --> F3["Authorization<br/>filter"]
    F3 -->|allowed| C["Controller"]
    F3 -->|"no login: 401<br/>no permission: 403"| X["Error response"]

A request must pass every filter before a controller sees it.

Authentication establishes an identity and stores it in the SecurityContext for the current request. Authorization compares that identity's authorities (roles and permissions) with the rules for the URL or method. Keeping the two apart explains the status codes: no valid identity gives 401 Unauthorized, an identity without permission gives 403 Forbidden.

Your own rules: SecurityFilterChain

You describe the policy by declaring a SecurityFilterChain bean. Boot's default one backs off as soon as yours exists, so it replaces everything you saw above, and you must state what you want:

Java
import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/public/**", "/error").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers(HttpMethod.POST, "/orders/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated())
            .formLogin(withDefaults())
            .httpBasic(withDefaults())
            .logout(withDefaults());
        return http.build();
    }
}

Read the rules from top to bottom: the first matching rule wins. That is why anyRequest().authenticated() always goes last, and why a broad permitAll() above a specific hasRole(...) silently makes the specific rule useless. The final catch-all is a security habit: new endpoints are protected unless someone deliberately opens them ("deny by default").

Two detail points. hasRole("ADMIN") checks for the authority ROLE_ADMIN; the ROLE_ prefix is added for you, and hasAuthority("ROLE_ADMIN") is the long form. And in modern Spring Security you configure everything with lambda blocks as above; the old and() chaining style is gone.

Boot 3 and 4 differ little here, but remember that you can define several SecurityFilterChain beans, each limited to a path with securityMatcher("/api/**") and ordered with @Order. A common split is a stateless chain for /api/** and a form-login chain for the human-facing pages.

A filter chain you can run

The stand-in below implements the same ideas without Spring: a request, a list of filters that call the next one, a Basic authentication filter, and an authorization filter with ordered rules where the first match wins. The user store keeps only password hashes (a toy SHA-256 here; the next section does it properly). The outputs show the 401 and 403 cases.

Java A security filter chain stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the order (authenticate, then authorize), first-match rules, and 401 versus 403. What is the stand-in: the real chain has about fifteen filters, a SecurityContextRepository that carries identity across requests (sessions or tokens), an AuthenticationManager with pluggable providers, exception translation, request matchers by pattern, and ROLE_ handling inside hasRole.

Users and password storage

Spring Security loads users through a UserDetailsService. For small tools there is an in-memory one; real applications implement the interface on top of their own user table:

Java
@Bean
UserDetailsService users(UserAccountRepository accounts) {
    return username -> accounts.findByEmail(username)
            .map(account -> User.withUsername(account.getEmail())
                    .password(account.getPasswordHash())
                    .roles(account.getRoles().toArray(String[]::new))
                    .build())
            .orElseThrow(() -> new UsernameNotFoundException("unknown user"));
}

@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

Never store passwords in plain text, and never use a fast hash such as MD5 or plain SHA-256. Passwords need a deliberately slow, salted, one-way function: bcrypt, scrypt, Argon2 or PBKDF2. A random salt per password makes identical passwords produce different hashes (so a leaked table cannot be attacked with precomputed lists), and the work factor makes each guess expensive for an attacker while costing a legitimate login only a fraction of a second.

createDelegatingPasswordEncoder() stores the algorithm in the hash itself, as $2a$10$.... At login it reads the prefix and picks the matching encoder. That lets an application move to a stronger algorithm over time: old hashes still verify, and upgradeEncoding tells you which ones to re-hash when the user next logs in. The JDK has no bcrypt, so this stand-in uses PBKDF2 (which Spring supports as Pbkdf2PasswordEncoder) to show the same behavior: random salt, work factor, a prefix that selects the algorithm, constant-time comparison and an upgrade path from a legacy hash.

Java A delegating password encoder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: PBKDF2 itself (from the JDK), salting, work factors and constant-time comparison; those are the actual techniques. What is the stand-in: Spring's DelegatingPasswordEncoder supports bcrypt (its default), scrypt, Argon2 and more behind the same prefix scheme, and adds Pbkdf2PasswordEncoder settings plumbing. In your code you only declare the bean and call passwordEncoder.encode(rawPassword) when a user registers; the framework calls matches at login.

Method security

URL rules are coarse. Sometimes the rule depends on the data: "an order can be read by its owner or an admin". Enable method security once and annotate service methods:

Java
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig { }

@Service
public class OrderService {

    @PreAuthorize("hasRole('ADMIN')")
    public List<Order> findAll() { /* ... */ }

    @PreAuthorize("#ownerId == authentication.name or hasRole('ADMIN')")
    public List<Order> findByOwner(String ownerId) { /* ... */ }

    @PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')")
    public Order findById(long id) { /* ... */ }
}

@PreAuthorize checks before the method runs, using a Spring expression language (SpEL) that can see the arguments (#ownerId) and the current user (authentication). @PostAuthorize checks after, with returnObject, which suits "load it, then check who owns it". Method security is applied through a proxy, so like @Transactional and @Cacheable it does not protect calls from inside the same class. Use URL rules for broad areas and method rules for ownership; use both for sensitive operations.

Common mistakes

  • Treating the UI as security. Hiding a button does not stop a request. Check on the server for every endpoint.
  • Rules in the wrong order. Put specific rules first and anyRequest() last.
  • Disabling CSRF for browser apps. Turn it off only for stateless APIs that use tokens, never for pages with cookie sessions.
  • Plain or fast-hashed passwords, and logging them. Use the delegating encoder, and keep credentials out of logs and toString.
  • Leaking whether a user exists. Return the same message for "unknown user" and "wrong password".
  • Shipping the generated password or users beyond a local demo.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an authenticated user without the required role receive?

    401 means the identity is missing or invalid. 403 means the identity is known but lacks permission.
  2. 2. Given these rules in order: anyRequest().authenticated() then requestMatchers("/admin/**").hasRole("ADMIN"), what happens?

    The catch-all matches every request first, so the specific rule below it is never reached. Always put anyRequest last.
  3. 3. Why does DelegatingPasswordEncoder write a prefix such as into the stored hash?

    The prefix selects the encoder at login, so you can move to a stronger algorithm without invalidating existing users.
  4. 4. Which is a correct way to store passwords?

    Salt defeats precomputed tables and the work factor makes guessing expensive; fast hashes and reversible encryption are the wrong tools.
  5. 5. What does @PreAuthorize("#ownerId == authentication.name") do?

    @PreAuthorize evaluates a SpEL expression before the call, with access to the arguments and the authentication object.

Summary

  • The starter locks everything and generates a development user; declare a SecurityFilterChain bean to state your own rules.
  • Requests pass through ordered filters: authentication establishes who you are, authorization decides what you may do (401 versus 403).
  • Rules are matched top to bottom, first match wins, and anyRequest().authenticated() belongs last.
  • Store passwords with a delegating encoder (bcrypt by default); salts and work factors are what make hashes safe.
  • @EnableMethodSecurity with @PreAuthorize adds data-dependent checks through a proxy.

Next: JWT and OAuth 2 Resource Server.