Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 119 ยท Spring Boot

Spring Security

How Spring Security protects a Spring Boot app - the security filter chain, authentication and authorization, SecurityFilterChain rules, password encoders and method security.

Every real application must answer two questions for each request: who is calling? (authentication) and are they allowed to do this? (authorization). Getting either one slightly wrong is how data leaks happen. Spring Security is the standard answer in the Spring world: a mature framework that authenticates users with passwords, tokens or single sign-on, enforces access rules on URLs and methods, hashes passwords properly, and adds protections against CSRF, clickjacking and session fixation by default.

Spring Security has a reputation for being hard, mostly because so much happens automatically. This lesson takes the mystery out of it. You will see the security filter chain that every request passes through, how authentication and the security context work, how to write a SecurityFilterChain configuration, how password encoders store passwords, and how method security protects services. The runnable examples rebuild each mechanism in plain Java, including a working filter chain with HTTP Basic authentication. You should know Web Security Basics, Filters and Listeners and Aspect-Oriented Programming first.

What happens when you add the starter

Add one dependency and restart:

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

Immediately, without any configuration:

  • Every endpoint requires authentication. Unauthenticated API calls get 401 Unauthorized; browsers are redirected to a generated login page.
  • There is one user, user, with a random password printed in the log at startup ("Using generated security password: ..."). This is for experiments only.
  • Form login and HTTP Basic are enabled, and logout works at /logout.
  • CSRF protection is on for state-changing requests (POST, PUT, DELETE).
  • Security headers are added to responses: X-Content-Type-Options: nosniff, X-Frame-Options: DENY, cache control for authenticated pages, and HSTS over HTTPS.

"Secure by default, then open up deliberately" is the right direction. The rest of this lesson is about opening up deliberately.

The security filter chain

Spring Security is built from servlet filters, so it runs before the DispatcherServlet and your controllers. One filter, DelegatingFilterProxy, is registered with the servlet container. It hands each request to Spring's FilterChainProxy, which picks the first matching SecurityFilterChain and runs its filters in order:

TEXT
Request โ”€โ–ถ DelegatingFilterProxy โ”€โ–ถ FilterChainProxy โ”€โ–ถ SecurityFilterChain (first that matches)
                                                            โ”‚
     SecurityContextHolderFilter      load/clear the SecurityContext for this request
     HeaderWriterFilter               add security headers
     CorsFilter                       answer CORS preflight requests
     CsrfFilter                       check the CSRF token on POST/PUT/DELETE
     LogoutFilter                     handle /logout
     UsernamePasswordAuthenticationFilter   process the login form
     BasicAuthenticationFilter        read "Authorization: Basic ..."
     BearerTokenAuthenticationFilter  read "Authorization: Bearer ..." (resource server)
     AnonymousAuthenticationFilter    no one authenticated? set an anonymous user
     ExceptionTranslationFilter       turn security exceptions into 401 / 403
     AuthorizationFilter              check the rules for this URL
                                                            โ”‚
                                                            โ–ผ
                                          DispatcherServlet โ”€โ–ถ your controller

Each filter has one job. The authentication filters look for credentials in their own format; if they find valid ones, they store an Authentication in the SecurityContextHolder. The AuthorizationFilter near the end checks the URL rules against that Authentication. If the check fails, it throws an exception, and the ExceptionTranslationFilter turns it into the right response:

  • 401 Unauthorized (with a WWW-Authenticate header for Basic): the caller is not authenticated, or the credentials were wrong. "Tell me who you are."
  • 403 Forbidden: the caller is authenticated but lacks permission. "I know who you are, and the answer is no."

Set logging.level.org.springframework.security=TRACE in development to see every filter a request passes through and why access was granted or denied.

Authentication and the SecurityContext

An Authentication object describes the current caller: the principal (usually a UserDetails with the username), the credentials (the password, erased after login) and the authorities (permissions such as ROLE_ADMIN or books:write). It lives in the SecurityContext, which SecurityContextHolder keeps in a ThreadLocal: anywhere in the same request thread, SecurityContextHolder.getContext().getAuthentication() returns it. In controllers you can simply ask for it:

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

Checking credentials is delegated: the AuthenticationManager (usually a ProviderManager) asks its AuthenticationProviders; for username and password that is the DaoAuthenticationProvider, which loads the user from a UserDetailsService and compares the password with a PasswordEncoder.

The program below is a working, simplified security filter chain on the JDK's HttpServer. It has a SecurityContextHolder based on ThreadLocal, a Basic authentication filter, an anonymous filter, an exception translation filter and an authorization filter with first-match-wins URL rules. A client then calls the API as an anonymous user, with a wrong password, as a normal user, as an editor and as an admin. The first request also prints the trace of filters it passed.

Java A working security filter chain

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.

Compare the results with the rules. POST /api/books gives 401 for anonymous callers and wrong passwords, but 403 for ada, who is authenticated but not an editor. grace is an editor but not an admin, so she gets 403 on /api/admin/stats. The anonymous GET /api/me is caught by the last rule, authenticated(). And the first filter clears the ThreadLocal in a finally block: servers reuse threads, so a forgotten context would let the next request run as the previous user.

Configuring a SecurityFilterChain

You configure Spring Security by defining a SecurityFilterChain bean, built with the HttpSecurity DSL. Here is a realistic configuration for a stateless JSON API with HTTP Basic (the next lesson replaces Basic with JWT bearer tokens):

Java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity                                         // enables @PreAuthorize, see below
public class SecurityConfig {

    @Bean
    SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/api/**")                       // this chain handles /api/** only
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/books/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers(HttpMethod.POST, "/api/books").hasRole("EDITOR")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable());                    // OK only because no cookies are used (see below)
        return http.build();
    }

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

Rules to remember:

  • Order matters: the first matching rule wins. Put specific rules first and anyRequest() last. If anyRequest().authenticated() came first, the admin rule would never be reached.
  • Deny by default. End with anyRequest().authenticated() (or denyAll()), so a new endpoint is protected even if someone forgets to add a rule.
  • hasRole("ADMIN") checks for the authority ROLE_ADMIN; the ROLE_ prefix is added for you. hasAuthority("books:write") checks an authority exactly, which suits fine-grained permissions.
  • Several SecurityFilterChain beans can coexist, for example one for /api/** (stateless, Basic or JWT) and one for the web pages (form login, sessions). Give them a securityMatcher and an @Order.
  • Spring Security 7 (Spring Boot 4) supports only this lambda DSL. Old examples with .and() chains, WebSecurityConfigurerAdapter or antMatchers(...) are from Spring Security 5 and no longer compile.

Where users come from

A UserDetailsService loads a user by name. For tests and demos, InMemoryUserDetailsManager is enough; for real applications, implement the interface over your own user table (or use JdbcUserDetailsManager):

Java
@Service
public class AccountUserDetailsService implements UserDetailsService {
    private final AccountRepository accounts;

    public AccountUserDetailsService(AccountRepository accounts) { this.accounts = accounts; }

    @Override
    public UserDetails loadUserByUsername(String username) {
        Account account = accounts.findByEmail(username)
            .orElseThrow(() -> new UsernameNotFoundException("No account " + username));
        return User.withUsername(account.getEmail())
            .password(account.getPasswordHash())                // e.g. "{bcrypt}$2a$10$..."
            .roles(account.getRoles().toArray(String[]::new))
            .disabled(!account.isActive())
            .build();
    }
}

Spring Security uses a bean of this type automatically. Its error messages to clients are deliberately vague ("Bad credentials" for both unknown users and wrong passwords), so attackers can't find out which accounts exist.

Password encoders

Passwords must be stored as slow, salted hashes, never as plain text or a fast hash like SHA-256 (Web Security Basics explains why). Spring Security's PasswordEncoder interface has two important methods, encode(raw) and matches(raw, stored), plus upgradeEncoding(stored).

The recommended setup is the DelegatingPasswordEncoder from PasswordEncoderFactories.createDelegatingPasswordEncoder(). It prefixes each stored hash with the algorithm id, for example:

TEXT
{bcrypt}$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy
{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc
{argon2}$argon2id$v=19$m=16384,t=2,p=1$...

New passwords are encoded with the current default (BCrypt), while old hashes keep working through their prefix. That lets you migrate algorithms without forcing a password reset: when a user logs in successfully with an outdated hash, Spring Security re-encodes the password with the current algorithm and saves it (through UserDetailsPasswordService). BCrypt's work factor (default 10) and PBKDF2's iteration count are tuned so that one hash takes roughly a tenth of a second or more on your server: unnoticeable for a login, very expensive for an attacker trying billions of guesses.

The JDK has no BCrypt, so the next program builds a delegating encoder around PBKDF2-HMAC-SHA256, which the JDK does include and which Spring Security also supports (Pbkdf2PasswordEncoder). It shows the salt making equal passwords hash differently, verification with a constant-time comparison, and the upgrade of an old password and an old low-iteration hash on login.

Java A delegating password encoder with PBKDF2

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.

The demo uses 20,000 PBKDF2 iterations only so that this page responds quickly. Spring Security's PBKDF2 defaults use 310,000 iterations, and the usual production choice is the default BCrypt (or Argon2) from createDelegatingPasswordEncoder(). Measure on your own hardware, and raise the cost as servers get faster; upgradeEncoding takes care of existing users.

Method security

URL rules protect endpoints, but some decisions depend on data: "users may read their own orders, admins may read all orders". @EnableMethodSecurity lets you annotate service methods with security expressions:

Java
@Service
public class OrderService {

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

    @PreAuthorize("hasRole('ADMIN') or #customer == authentication.name")
    public List<Order> findByCustomer(String customer) { ... }

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

@PreAuthorize checks before the method runs, and can refer to parameters by name (#customer). @PostAuthorize checks the return value. Failures throw AccessDeniedException, which becomes a 403. For complex rules, call a bean from the expression: @PreAuthorize("@orderAccess.canRead(#id, authentication)").

Method security is implemented with proxies, just like @Transactional. That means the same limitation from Aspect-Oriented Programming: calling an annotated method from another method of the same class bypasses the proxy, and with it the check. Here is the mechanism with java.lang.reflect.Proxy, a tiny expression evaluator and a ThreadLocal security context:

Java How @PreAuthorize works: a security proxy

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.

The last line is the warning made visible: the raw object hands every order to ada. In Spring, that happens when an unannotated method in OrderService calls this.findAll(). Keep secured methods on the public API of a bean, and call them through the injected bean.

CSRF, CORS and sessions

  • CSRF protection matters whenever the browser sends credentials automatically, which means session cookies. Keep it enabled for server-rendered apps with form login (Thymeleaf adds the token to forms automatically) and for single-page apps that use cookies (use CookieCsrfTokenRepository.withHttpOnlyFalse() so the JavaScript client can read the token and send it back in a header; recent versions also offer a csrf(csrf -> csrf.spa()) shortcut). Disabling it is safe only for APIs whose clients send a token in the Authorization header and never rely on cookies.
  • CORS controls which other origins may call your API from a browser. Configure it in Spring Security with http.cors(Customizer.withDefaults()) plus a CorsConfigurationSource bean listing allowed origins, methods and headers. Never combine allowedOrigins("*") with credentials.
  • Sessions: form login stores the SecurityContext in the HTTP session and changes the session id at login (session-fixation protection). Stateless APIs use SessionCreationPolicy.STATELESS and authenticate every request, usually with a token. See Sessions and Cookies.

CORS in detail

Browsers enforce the same-origin policy: a page from https://shop.example may not read the response of an API at https://api.example unless that API opts in with CORS headers. For "non-simple" requests (JSON bodies, an Authorization header, methods like PUT and DELETE) the browser first sends a preflight OPTIONS request with Origin, Access-Control-Request-Method and Access-Control-Request-Headers, and only continues if the answer allows it. The answer is made of these headers:

Response header Meaning Spring setting
Access-Control-Allow-Origin the origin that may read the response allowedOrigins / allowedOriginPatterns
Access-Control-Allow-Methods methods allowed in the real request allowedMethods
Access-Control-Allow-Headers request headers the page may send allowedHeaders
Access-Control-Allow-Credentials cookies and HTTP auth may be included allowCredentials(true)
Access-Control-Expose-Headers extra response headers JavaScript may read (such as Location) exposedHeaders
Access-Control-Max-Age how long the browser may cache the preflight answer maxAge

Spring offers three places to configure it. A single controller or method can use @CrossOrigin; MVC-wide rules go in a WebMvcConfigurer; and with Spring Security you register a CorsConfigurationSource bean and enable cors(), so the CORS filter runs before authentication and the preflight, which carries no credentials, is not rejected with 401:

Java
@RestController
@CrossOrigin(origins = "https://shop.example", maxAge = 3600)      // this controller only
class ProductController { /* ... */ }

@Bean
CorsConfigurationSource corsConfigurationSource() {
    var config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://shop.example"));       // never "*" together with credentials
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    config.setExposedHeaders(List.of("Location"));
    config.setAllowCredentials(true);
    config.setMaxAge(Duration.ofHours(1));

    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http.cors(Customizer.withDefaults())                      // picks up the bean above
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .build();
}

The TryIt applies the same decision logic to a preflight and to a real request, so you can see why a wrong origin, method or header makes the browser refuse. It is a stand-in: the real work happens in Spring's CorsFilter and the browser.

Java The CORS decision for a preflight request

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.

Remember that CORS is a browser rule: it does not stop curl, a server or a script from calling your API, so it never replaces authentication.

Testing secured endpoints

Security rules are code and need tests. With spring-security-test (included in the Boot test setup when Security is present), @WebMvcTest loads your SecurityFilterChain, and you choose the caller per test:

Java
@WebMvcTest(BookController.class)
@Import(SecurityConfig.class)
class BookSecurityTest {
    @Autowired MockMvc mvc;
    @MockitoBean BookService books;

    @Test
    void anonymousCannotCreate() throws Exception {
        mvc.perform(post("/api/books").contentType(APPLICATION_JSON).content("{}"))
           .andExpect(status().isUnauthorized());
    }

    @Test
    @WithMockUser(roles = "USER")
    void userWithoutEditorRoleIsForbidden() throws Exception {
        mvc.perform(post("/api/books").contentType(APPLICATION_JSON).content("{}"))
           .andExpect(status().isForbidden());
    }

    @Test
    void basicCredentialsAreChecked() throws Exception {
        mvc.perform(get("/api/me").with(httpBasic("grace", "wrong")))
           .andExpect(status().isUnauthorized());
    }
}

Test the denials, not just the happy path: a rule that accidentally permits everyone passes every "allowed" test. See Testing Spring Boot Applications for the testing basics.

Custom login pages, handlers and remember-me

The generated login page is fine for a demo. A real server-rendered application replaces it, decides where users land after logging in or out, and often offers "keep me signed in". All of this hangs off the formLogin, logout and rememberMe parts of the same SecurityFilterChain DSL. Spring cannot run in this page's editor, so the configuration below is read-only and the two examples after it are plain-Java stand-ins for the interesting logic.

Your own login page

You provide a page, tell Spring Security its URL, and Spring Security keeps processing the POST for you:

Java
@Bean
SecurityFilterChain webSecurity(HttpSecurity http,
                                AuthenticationSuccessHandler successHandler,
                                AuthenticationFailureHandler failureHandler) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/login", "/css/**", "/register").permitAll()   // the login page itself must be public
            .anyRequest().authenticated())
        .formLogin(form -> form
            .loginPage("/login")                       // GET: your controller renders the page
            .loginProcessingUrl("/login")              // POST: handled by Spring Security's filter
            .usernameParameter("email")                // names of the form fields (defaults: username, password)
            .passwordParameter("password")
            .successHandler(successHandler)
            .failureHandler(failureHandler))
        .logout(logout -> logout
            .logoutUrl("/logout")                      // POST by default, protected by CSRF
            .logoutSuccessUrl("/login?logout")
            .invalidateHttpSession(true)
            .deleteCookies("JSESSIONID", "remember-me"));
    return http.build();
}

The page is a normal Thymeleaf template (Thymeleaf). Thymeleaf adds the CSRF token to th:action forms for you, which is why th:action matters here:

HTML
<!-- templates/login.html -->
<form th:action="@{/login}" method="post">
  <p th:if="${param.error}" class="error">Wrong email or password.</p>
  <p th:if="${param.logout}">You have been signed out.</p>
  <label>Email <input type="email" name="email" required></label>
  <label>Password <input type="password" name="password" required></label>
  <label><input type="checkbox" name="remember-me"> Keep me signed in</label>
  <button type="submit">Sign in</button>
</form>

Beware of making the error message more helpful than "wrong email or password". Telling visitors "no such user" versus "wrong password" lets an attacker test which emails have accounts.

Success and failure handlers

Without a handler, a successful login sends the user to the page they originally asked for (the saved request, kept in the session) or to defaultSuccessUrl. A handler lets you add logic: role-based landing pages, audit records, resetting a failure counter.

Java
@Component
class RoleAwareSuccessHandler implements AuthenticationSuccessHandler {

    private final RequestCache requestCache = new HttpSessionRequestCache();
    private final RedirectStrategy redirects = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        SavedRequest saved = requestCache.getRequest(request, response);
        if (saved != null) {                                  // they were sent to /login from somewhere
            requestCache.removeRequest(request, response);
            redirects.sendRedirect(request, response, saved.getRedirectUrl());
            return;
        }
        boolean admin = authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
        redirects.sendRedirect(request, response, admin ? "/admin" : "/dashboard");
    }
}

@Component
class LoggingFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        log.warn("Login failed for {} from {}: {}", request.getParameter("email"),
                 request.getRemoteAddr(), exception.getClass().getSimpleName());
        response.sendRedirect("/login?error");
    }
}

The exception tells you why the login failed: BadCredentialsException, LockedException, DisabledException (not yet activated) or AccountExpiredException. You can send each reason to a different message, but keep the wording of the public message about unknown users and wrong passwords the same.

A frequent request is "redirect back to the page they were on", for example from a ?redirectTo= parameter you put in the login link. Never redirect to a user-supplied URL unchecked, because that is an open redirect: an attacker mails a victim a real login link whose parameter points at a phishing site. Only follow paths that start with a single /, as the second example below does. (Spring Security's own saved-request mechanism is safe, because it records only the URL of a request your app received.)

Logout handlers

logoutSuccessUrl is enough for most apps. When something else must happen on logout, such as revoking a refresh token or writing an audit entry, add a LogoutHandler (runs while the session is still available) or a LogoutSuccessHandler (decides the response):

Java
.logout(logout -> logout
    .addLogoutHandler((request, response, authentication) -> {
        if (authentication != null) {
            auditLog.record(authentication.getName(), "LOGOUT");
        }
    })
    .logoutSuccessHandler((request, response, authentication) ->
            response.sendRedirect("/login?logout")))

Remember that logging out with a GET link is blocked while CSRF protection is on. Use a small POST form with a button, or you end up disabling CSRF protection for the sake of a hyperlink.

Remember-me

Remember-me keeps users signed in after the session ends by giving the browser a second cookie. There are two designs, and the difference matters:

Hash-based (TokenBasedRememberMeServices) Persistent token (PersistentTokenBasedRememberMeServices)
Cookie contains username, expiry time, and a hash of both plus the password hash and a secret key a series id and a random token
Server stores nothing one row per browser: username, series, token, last used
Stolen cookie works until it expires or the password changes works once; theft is detected when the real user returns
Logout on one device cannot revoke just that cookie deletes that series

For anything beyond a toy, choose the persistent version, with the standard JDBC repository (persistent_logins table: username, series as primary key, token, last_used):

Java
.rememberMe(remember -> remember
    .key(rememberMeSecret)                           // from configuration, not source code
    .tokenRepository(new JdbcTokenRepositoryImpl() {{ setDataSource(dataSource); }})
    .tokenValiditySeconds(14 * 24 * 60 * 60)         // two weeks
    .rememberMeParameter("remember-me")
    .userDetailsService(userDetailsService))

On every automatic login the server rotates the token: it keeps the series, creates a new random token and sets a new cookie. If a cookie arrives with a right series but a wrong token, somebody has used an old copy, either an attacker or the victim after the attacker. Spring then throws CookieTheftException and removes all of that user's remember-me rows, which forces a real login.

Remember-me authentication is weaker than a password login, so mark sensitive actions (changing the email address, paying) as needing a fully authenticated user: .requestMatchers("/account/security/**").fullyAuthenticated() rejects remember-me sessions and sends them to the login form.

Java Persistent remember-me tokens with theft detection

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.

Output of the real thing differs only in names and storage (a table, a Set-Cookie header), but the rotation and the all-rows-deleted reaction are the same.

Extra login fields and database-backed login

Sometimes a login needs more than a username and password: a tenant or company code, a captcha answer, a one-time code. Spring Security has an extension point for exactly that. A custom AuthenticationDetailsSource captures extra request parameters into the Authentication details, and your AuthenticationProvider (or UserDetailsService, for tenant lookup) reads them:

Java
public class TenantWebAuthenticationDetails extends WebAuthenticationDetails {
    private final String tenant;

    public TenantWebAuthenticationDetails(HttpServletRequest request) {
        super(request);
        this.tenant = request.getParameter("tenant");
    }

    public String getTenant() { return tenant; }
}

// in the DSL:
.formLogin(form -> form
    .authenticationDetailsSource(TenantWebAuthenticationDetails::new))

Reading the tenant inside a provider is then ((TenantWebAuthenticationDetails) auth.getDetails()).getTenant(). Prefer this approach to writing your own filter: the standard filter keeps CSRF checks, session-fixation protection, remember-me and the success/failure handlers working.

Database-backed login is the UserDetailsService you saw earlier: load the user row, return the hash with its prefix and map your active, locked and roles columns to User.builder()'s disabled, accountLocked and roles. For a quick start, JdbcUserDetailsManager reads the standard users and authorities tables with no code at all; once your table has its own shape, write the service. A DaoAuthenticationProvider then does the comparison with the PasswordEncoder, throws the right exception subclasses, and calls your handlers.

The second example is the decision logic of a success handler in plain Java: saved request first (but only a safe local path), then a role-based landing page.

Java Where should a successful login go?

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.

Check your understanding

Quick check ยท 6 questions

of 6 answered You scored / 6 ยท perfect!

  1. 1. An authenticated user without the ADMIN role calls an endpoint that requires hasRole('ADMIN'). Which status should the response have?

    The caller is known but not allowed. 401 means "not authenticated", 403 means "authenticated but not permitted".
  2. 2. The rules are: anyRequest().authenticated(), then requestMatchers("/api/admin/**").hasRole("ADMIN"). What is wrong?

    Authorization rules are checked in order. Put the most specific rules first and anyRequest() last.
  3. 3. Why does a DelegatingPasswordEncoder store hashes like {bcrypt}$2a$10$...?

    The id selects the encoder for matching. New passwords use the default algorithm, and upgradeEncoding triggers re-encoding of outdated hashes.
  4. 4. A service method has @PreAuthorize("hasRole('ADMIN')"). Another method in the same class calls it as this.deleteAll(). What happens?

    Like @Transactional, method security is applied by a proxy around the bean. Calls through this never reach the proxy.
  5. 5. When is it reasonable to disable CSRF protection?

    CSRF attacks abuse credentials that the browser sends automatically, such as session cookies. Without such credentials, there is nothing to forge.
  6. 6. A cookie with a valid remember-me series but an old token arrives at a persistent-token remember-me setup. What does Spring Security do?

    Tokens rotate on each use, so an old token means the cookie was copied and used elsewhere. All of the user's remembered logins are removed and a real login is needed.

Summary

  • Spring Security is a chain of servlet filters running before the DispatcherServlet; FilterChainProxy picks the first matching SecurityFilterChain.
  • Authentication filters put an Authentication (principal + authorities) into the ThreadLocal SecurityContextHolder; the AuthorizationFilter checks URL rules; the ExceptionTranslationFilter turns failures into 401 (not authenticated) or 403 (not permitted).
  • Configure a SecurityFilterChain bean with the lambda DSL: authorizeHttpRequests rules (first match wins, anyRequest() last), httpBasic/formLogin, session policy, CSRF and CORS.
  • hasRole("X") checks the authority ROLE_X; hasAuthority checks exact permissions.
  • Users come from a UserDetailsService; passwords are checked by a PasswordEncoder. Use createDelegatingPasswordEncoder() (BCrypt by default) and let upgradeEncoding migrate old hashes.
  • @EnableMethodSecurity with @PreAuthorize/@PostAuthorize protects service methods with data-dependent rules, through proxies (self-invocation bypasses them).
  • Customize form login with loginPage, success/failure handlers and logout handlers; never redirect to an unchecked user-supplied URL. Remember-me should use rotating persistent tokens, and sensitive actions can demand fullyAuthenticated().
  • Keep CSRF on for cookie-based authentication; test both allowed and denied cases with @WithMockUser and httpBasic(...).

Next: JWT and OAuth 2 replaces passwords on every request with signed tokens, and explains OAuth 2 and OpenID Connect login flows.