Skip to content
notes.vinhnq.com

Search

SecurityMid19 min read

Form login with Spring Security: the filter chain, UserDetailsService and role-based access

Review 17 cards
On this page

Spring MVC end to end series: 1. Maven and project layout · 2. DispatcherServlet and views · 3. Forms and validation · 4. Form login with Spring Security · 5. Sessions and remember-me · 6. File upload · 7. Cart and checkout · 8. Pagination and dynamic filters

This post builds form login for a server-rendered shop: users come from the database, the login page is our own, guests browse freely, the cart needs a login, and /admin is for ADMIN only. Afterwards you can draw a request’s path through Spring Security, name the class that does each step of a login, and avoid the common configuration mistakes. Sessions, cookies and JWT theory live in authentication with session cookies and JWT; CSRF lives in web attacks and the OWASP Top 10.

1. Where Spring Security sits: from servlet filter to SecurityFilterChain

Key idea: Spring Security doesn’t live in your controllers; it’s servlet filters wrapped around the DispatcherServlet. Tomcat knows a single filter called springSecurityFilterChain, and that filter hands the work to Spring beans.

A servlet filter is code that runs before and after the servlet for each request and may change the request or stop it. Tomcat creates filters before the Spring context is ready, so Spring needs a bridge:

flowchart LR
  T[Tomcat] --> D[DelegatingFilterProxy]
  D --> F[FilterChainProxy]
  F --> C1{Which SecurityFilterChain matches?}
  C1 -->|/api/**| A[API chain]
  C1 -->|everything else| W[Web chain: 15 filters]
  W --> S[DispatcherServlet]
  S --> K[Controller]
  • DelegatingFilterProxy: the real servlet filter. It just looks up the bean named springSecurityFilterChain in the Spring context and calls it.
  • FilterChainProxy: holds the list of SecurityFilterChains, picks the first one matching the request (by securityMatcher), and runs its filters. It also runs the HttpFirewall, which rejects odd URLs (containing //, ;, encoded .. and so on).
  • SecurityFilterChain: the bean you declare with HttpSecurity. An app may have several, for example a stateless chain for /api/** and a form-login chain for the rest (JWT setup in the authentication post, section 7).

The filter order in the lab’s chain, taken from a real stack trace while running the tests:

Filter Main job
DisableEncodeUrlFilter keeps the session id out of URLs
WebAsyncManagerIntegrationFilter carries the SecurityContext to async threads
SecurityContextHolderFilter loads the SecurityContext (from the session) into SecurityContextHolder
HeaderWriterFilter adds security headers (X-Frame-Options, nosniff, Cache-Control…)
CsrfFilter rejects POST/PUT/PATCH/DELETE without a valid CSRF token
LogoutFilter handles POST /logout
UsernamePasswordAuthenticationFilter handles POST /login, checks username/password
ConcurrentSessionFilter kicks out sessions marked expired (session limits)
RequestCacheAwareFilter restores the request saved before the login redirect
SecurityContextHolderAwareRequestFilter makes request.isUserInRole() and request.logout() work
RememberMeAuthenticationFilter logs in again from a remember-me cookie
AnonymousAuthenticationFilter attaches an “anonymous” user when nobody is logged in
SessionManagementFilter session policy
ExceptionTranslationFilter turns authentication errors into a login redirect/401, access errors into 403
AuthorizationFilter checks the authorizeHttpRequests rules, always last

The order has reasons: CSRF must be checked before the login is processed, and AuthorizationFilter comes last so every authentication filter has already run. Which filters appear depends on configuration: turn off rememberMe and RememberMeAuthenticationFilter is gone.

How to see your own app’s real chain
  • Set logging.level.org.springframework.security=DEBUG: at startup Spring logs Will secure any request with [...] listing every filter; each request logs Securing GET /cart and which filters ran.
  • Put a breakpoint in FilterChainProxy.doFilterInternal and look at the filters variable.
  • With two chains, declare the specific one first with securityMatcher("/api/**") and the chain without a matcher last, because FilterChainProxy stops at the first match. Use @Order if they live in different classes.

The lab’s stack trace also shows Spring Session’s SessionRepositoryFilter sitting before DelegatingFilterProxy: it must swap the HttpSession before Spring Security reads the session (part 5).

2. Defaults right after adding the starter

Key idea: add spring-boot-starter-security and every URL requires login, with a generated login page and a temporary user. That’s a safe starting point, not a configuration to ship.

  • Every request must be authenticated, CSS and JS included.
  • Generated /login and /logout pages, plus HTTP Basic.
  • One user called user with a random password printed in the startup log. spring.security.user.name/password change it: this user lives in memory (InMemoryUserDetailsManager) and is for demos only.
  • CSRF on, security headers on, session id changed after login.

Once you declare your own SecurityFilterChain bean, the default chain disappears and every rule is your responsibility. Declare a UserDetailsService bean and the temporary user disappears.

Trap: switching security off to code faster

3. The form login flow: which classes take part

Key idea: the filter takes username and password, ProviderManager delegates to DaoAuthenticationProvider, which loads the user through UserDetailsService and compares the password with PasswordEncoder. On success the SecurityContext is saved in the session.

sequenceDiagram
    participant B as Browser
    participant F as UsernamePasswordAuthenticationFilter
    participant M as ProviderManager
    participant P as DaoAuthenticationProvider
    participant U as UserDetailsService
    participant R as SecurityContextRepository
    B->>F: POST /login (email, password, _csrf)
    F->>M: authenticate(unauthenticated token)
    M->>P: authenticate
    P->>U: loadUserByUsername(email)
    U-->>P: UserDetails (hash, authorities)
    P->>P: PasswordEncoder.matches, check locked and expired
    P-->>F: authenticated Authentication
    F->>R: save SecurityContext in the session
    F-->>B: 302 to the post-login page
  1. UsernamePasswordAuthenticationFilter only handles POST /login. It reads two parameters (username and password by default) and builds an unauthenticated UsernamePasswordAuthenticationToken.
  2. The AuthenticationManager (implemented by ProviderManager) asks each AuthenticationProvider whether it supports this token type.
  3. DaoAuthenticationProvider calls UserDetailsService.loadUserByUsername, checks whether the account is locked, disabled or expired, then runs passwordEncoder.matches(raw, hash).
  4. On success: change the session id (against session fixation), save the SecurityContext through the SecurityContextRepository (by default the SPRING_SECURITY_CONTEXT attribute of the HttpSession), call the success handler.
  5. Next request: SecurityContextHolderFilter loads the context from the session, lazily (only when some code asks). That’s why, when debugging, you have to look at deferredContext.get().

If you write your own login endpoint instead of formLogin, step 4 doesn’t happen by itself: see the TIL on SecurityContextRepository in the authentication post.

4. Your own UserDetailsService and PasswordEncoder

Key idea: UserDetailsService has one job: from a username, return UserDetails (password hash, authorities, status). Keep that object small, because it sits in the session for the whole visit.

public record ShopUserDetails(Long id, String email, String passwordHash, String role) implements UserDetails {
    static ShopUserDetails from(AppUser u) {
        return new ShopUserDetails(u.getId(), u.getEmail(), u.getPasswordHash(), u.getRole().name());
    }
    @Override public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of(new SimpleGrantedAuthority("ROLE_" + role));      // role comes from the DB
    }
    @Override public String getPassword() { return passwordHash; }
    @Override public String getUsername() { return email; }
}

@Service
public class DbUserDetailsService implements UserDetailsService {
    private final UserRepository users;
    public DbUserDetailsService(UserRepository users) { this.users = users; }

    @Override
    public UserDetails loadUserByUsername(String email) {
        return users.findByEmailIgnoreCase(email).map(ShopUserDetails::from)
                .orElseThrow(() -> new UsernameNotFoundException("not found"));
    }
}
  • A dedicated record, not the entity: the principal is serialized into the session. A JPA entity drags lazy proxies and its whole relationship graph along and breaks easily on serialization (part 5). The record carries id, so controllers get the user id through @AuthenticationPrincipal ShopUserDetails me without another query.
  • Case-insensitive email: the test logs in as ADMIN@shop.dev and succeeds.
  • Don’t call your entity User: the course material has to spell out vn.hoidanit...domain.User because it clashes with org.springframework.security.core.userdetails.User. Naming it AppUser ends the confusion.
  • PasswordEncoder: PasswordEncoderFactories.createDelegatingPasswordEncoder() stores hashes as {bcrypt}$2a$10$.... The {id} prefix lets you switch algorithms later while old hashes still verify. Choosing the algorithm and its cost: storing passwords.

5. Your own login page and CSRF in forms

Key idea: loginPage("/login") means GET /login is served by your controller, while POST /login is still handled by the filter. The form must send the right parameter names and a CSRF token.

<form th:action="@{/login}" method="post">
  <p th:if="${param.error}">Wrong email or password</p>
  <p th:if="${param.logout}">You have been logged out</p>
  <input name="email"> <input type="password" name="password">
  <label><input type="checkbox" name="remember-me"> Remember me</label>
  <button>Log in</button>
</form>
  • usernameParameter("email") because the form uses name="email"; without it the filter looks for username and always fails.
  • failureUrl("/login?error"): a generic message that doesn’t say whether the email or the password was wrong.
  • th:action inserts <input type="hidden" name="_csrf" value="..."> by itself: I fetched GET /login in the lab and the input is in the HTML. With JSP you write <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> yourself.
  • A missing token means 403, even on the login form: test loginWithoutCsrfIsForbidden. How CSRF works and why you keep it on with session cookies: web attacks, section 4.

AJAX calls (add to cart without reloading) must send the token too, in a header:

<meta name="_csrf" th:content="${_csrf.token}">
<meta name="_csrf_header" th:content="${_csrf.headerName}">
<script>
  const token = document.querySelector('meta[name=_csrf]').content;
  const header = document.querySelector('meta[name=_csrf_header]').content;   // "X-CSRF-TOKEN"
  fetch('/cart/items', { method: 'POST', headers: { [header]: token },
                         body: new URLSearchParams({ productId: 7 }) });
</script>

6. URL authorization: rule order, hasRole and hasAuthority

Key idea: rules in authorizeHttpRequests are checked top-down and the first match decides. Go from specific to general and finish with anyRequest().authenticated().

.authorizeHttpRequests(a -> a
    .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
    .requestMatchers("/", "/products/**", "/login", "/register", "/access-denied",
                     "/css/**", "/js/**", "/files/**").permitAll()
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .anyRequest().authenticated())
Expression Authority string checked Use for
hasRole("ADMIN") ROLE_ADMIN (prefix added) coarse, role-based access
hasAuthority("ROLE_ADMIN") exactly ROLE_ADMIN same as above
hasAuthority("order:refund") exactly order:refund fine-grained permissions, OAuth2 scopes

Because hasRole adds ROLE_, don’t write hasRole("ROLE_ADMIN") (Spring fails at startup). Conversely, UserDetails must return authorities with the prefix.

URL rules are the outer layer. The inner layer is method security: enable @EnableMethodSecurity and put @PreAuthorize("hasRole('ADMIN')") or @PreAuthorize("#userId == authentication.principal.id") on services. Data-dependent checks (“only the order’s owner can see it”) belong in that layer or in the query. Designing roles and permissions: RBAC authorization.

Not logged in and not allowed take two different paths in ExceptionTranslationFilter:

  • Anonymous opens /cart → AuthenticationEntryPoint → redirect to /login (test anonymousIsRedirectedToLoginForCart).
  • A USER opens /admin → AccessDeniedHandler → 403, forward to /access-denied (test userCannotOpenAdmin).

7. After login: redirect by role and the saved request

Key idea: ADMIN goes to /admin, a USER goes back to the page they were trying to open before being asked to log in. Extending SavedRequestAwareAuthenticationSuccessHandler gives you both.

When an anonymous user opens /checkout, ExceptionTranslationFilter saves that request (the saved request) in the session and then redirects to login. After login, the default handler reads it back and sends the user to /checkout?continue. The continue parameter is Spring Security 6’s way of telling RequestCacheAwareFilter that now is the time to check the session, instead of checking on every request.

@Component
public class RoleRedirectSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public RoleRedirectSuccessHandler() { setDefaultTargetUrl("/"); }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth)
            throws IOException, ServletException {
        boolean admin = auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
        if (admin) {
            clearAuthenticationAttributes(req);
            getRedirectStrategy().sendRedirect(req, res, "/admin");
            return;
        }
        super.onAuthenticationSuccess(req, res, auth);     // saved request or "/"
    }
}

Tests userLoginRedirectsHomeAdminLoginRedirectsAdmin and savedRequestIsRestoredAfterLogin cover all three branches. The course’s approach (based on SimpleUrlAuthenticationSuccessHandler, redirecting by role only) loses the saved request: a customer clicks “Checkout”, logs in, and lands on the home page again.

Trap: accepting a target URL after login

8. Logout and the 403 page

Key idea: logout changes state, so it must be a POST with a CSRF token. LogoutFilter invalidates the session, clears the SecurityContext and the remember-me cookie, then redirects.

<form th:action="@{/logout}" method="post"><button>Log out</button></form>
  • I tried GET /logout in the lab while logged in: 404, and still logged in. An <a href="/logout"> in the menu therefore does nothing; it must be a POST form (styled as a link if you like).
  • logoutSuccessUrl("/login?logout") lets the login page show a message; the test posts /logout with CSRF and gets exactly that URL.
  • To show the logged-in user’s name in the header, add thymeleaf-extras-springsecurity6 and use sec:authorize="isAuthenticated()" and sec:authentication="name". JSP uses the security taglib. I didn’t put this in the lab.
  • Your own 403 page: exceptionHandling(e -> e.accessDeniedPage("/access-denied")), and remember to permitAll that URL.

Exercises

Task (the course lab, restated): a server-rendered laptop shop. (1) Everyone can see the home page and product pages. (2) Cart and checkout need a login. (3) /admin/** is for ADMIN only. (4) Log in with email and password stored in the database, using your own login page, with an error message on failure. (5) ADMIN lands on /admin after login, USER on the home page. (6) Logout and a custom 403 page.

Solution: the full SecurityConfig and tests

Run on Spring Boot 3.5.9, Java 21, H2, mvn test: the lab’s 23 tests plus 4 I added (CSRF input on the login page, GET /logout doesn’t log out, POST /logout, AJAX gets 401) all pass.

@Configuration
@EnableMethodSecurity
public class SecurityConfig {
    @Bean PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }

    @Bean
    SecurityFilterChain web(HttpSecurity http, RoleRedirectSuccessHandler success) throws Exception {
        http
            .authorizeHttpRequests(a -> a
                .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
                .requestMatchers("/", "/products/**", "/login", "/register", "/access-denied",
                                 "/css/**", "/js/**", "/files/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .formLogin(f -> f
                .loginPage("/login")
                .usernameParameter("email")
                .successHandler(success)
                .failureUrl("/login?error")
                .permitAll())
            .logout(l -> l.logoutSuccessUrl("/login?logout"))
            .exceptionHandling(e -> e.accessDeniedPage("/access-denied"));
        // rememberMe and sessionManagement: part 5
        return http.build();
    }
}

The login page controller only returns a view, with no leading /:

@GetMapping("/login") String login() { return "auth/login"; }
@GetMapping("/access-denied") String denied() { return "auth/denied"; }

Representative tests (MockMvc + spring-security-test):

@Test void loginWithoutCsrfIsForbidden() throws Exception {
    mvc.perform(post("/login").param("email", "alice@shop.dev").param("password", "password1"))
       .andExpect(status().isForbidden());
}
@Test void savedRequestIsRestoredAfterLogin() throws Exception {
    MvcResult r = mvc.perform(get("/checkout")).andExpect(status().is3xxRedirection()).andReturn();
    Cookie session = r.getResponse().getCookie("SESSION");
    mvc.perform(post("/login").with(csrf()).cookie(session)
                .param("email", "alice@shop.dev").param("password", "password1"))
       .andExpect(redirectedUrlPattern("**/checkout?continue"));
}
@Test void userCannotOpenAdmin() throws Exception {
    mvc.perform(get("/admin").with(user(me(alice)))).andExpect(status().isForbidden())
       .andExpect(forwardedUrl("/access-denied"));
    mvc.perform(get("/admin").with(user(me(admin)))).andExpect(status().isOk());
}

What a senior would add:

  • Tests for every important URL rule (a “URL × role → status” table) in CI, so a new endpoint can’t open by accident.
  • Throttling of failed logins per IP and per account (rate limit, temporary lock), and logging AuthenticationFailureBadCredentialsEvent to spot password guessing.
  • Data-level checks in services (@PreAuthorize or a condition in the query), not just URL rules.
  • A CSP header and a __Host- + Secure cookie (configured in web attacks, section 7).
  • Re-asking for the password before sensitive actions (changing email or password), using fullyAuthenticated().

Remember

  • Can you draw DelegatingFilterProxy → FilterChainProxy → SecurityFilterChain → filters → DispatcherServlet, and say why AuthorizationFilter comes last?
  • Can you name the classes in one form login and where the SecurityContext ends up?
  • Can you explain why GET /login is yours but POST /login isn’t, and what the form must contain?
  • Can you tell hasRole from hasAuthority, and redirect/401 from 403?
  • Do you know why logout is a POST and why hideUserNotFoundExceptions(false) stays off?

Interview questions

Junior

Where does Spring Security stop a request, relative to the controller?

At the servlet filter level, before the request reaches the DispatcherServlet, so a rejected request never touches a controller.

Tomcat calls DelegatingFilterProxy, which hands off to the FilterChainProxy bean. FilterChainProxy picks the first SecurityFilterChain matching the URL and runs its filters: CSRF, login, remember-me, authorization and so on.

What’s the difference between hasRole(“ADMIN”) and hasAuthority(“ADMIN”)?

hasRole("ADMIN") checks the authority ROLE_ADMIN (it adds the prefix); hasAuthority("ADMIN") checks the exact string ADMIN.

If UserDetails returns ROLE_ADMIN and the rule says hasAuthority("ADMIN"), the admin gets a 403. Convention: roles carry the ROLE_ prefix, fine-grained permissions (order:refund) use hasAuthority.

Why must logout be a POST?

Because logout changes state; if GET worked, an <img src="/logout"> on any other site could log users out.

With CSRF on, Spring Security only accepts POST /logout with a CSRF token by default. GET /logout goes straight to the DispatcherServlet and is usually a 404.

Mid

Walk through the steps from clicking “Log in” to the next request being recognised.

Filter reads the form → ProviderManager → DaoAuthenticationProvider loads the user and checks the hash → session id changes → SecurityContext saved in the session → redirect; on the next request SecurityContextHolderFilter loads the context back from the session.

UsernamePasswordAuthenticationFilter builds an unauthenticated token. DaoAuthenticationProvider calls UserDetailsService and PasswordEncoder.matches and checks lock/expiry. On success, SessionAuthenticationStrategy changes the id and enforces session limits, SecurityContextRepository stores the SPRING_SECURITY_CONTEXT attribute, and the success handler redirects.

What does a logged-out user get versus a user without permission, and who decides?

ExceptionTranslationFilter decides: not logged in goes through the AuthenticationEntryPoint (login redirect or 401), logged in but not allowed goes through the AccessDeniedHandler (403).

For web forms the entry point redirects to /login; for AJAX or APIs it should return 401. To have both, declare defaultAuthenticationEntryPointFor for each matcher, including an “any other request” one, otherwise the first entry point declared becomes the default for everything.

You enable Spring Security 6 and JSP pages go into a redirect loop. Why?

Because Spring Security 6 also authorizes forward dispatches; rendering a JSP is a forward to /WEB-INF/...jsp, which isn’t permitted, so it triggers a login, and the login page is a JSP as well.

Fix: dispatcherTypeMatchers(FORWARD, ERROR).permitAll() at the top of the rules. The “malicious String //” error has the same root: a view name with a leading / plus the prefix produces //, which StrictHttpFirewall rejects.

Why shouldn’t the principal be a JPA entity?

The principal lives in the SecurityContext, i.e. in the session, so it gets serialized; an entity brings lazy proxies, relationships and stale data, and it’s heavy and fragile.

Use a small record (id, email, hash, role) implementing UserDetails. Controllers get the id via @AuthenticationPrincipal, and data that changes (name, avatar) is read from the database when needed.

Senior

Assess the setting setHideUserNotFoundExceptions(false).

Don’t use it: it separates “no such user” from “wrong password”, which helps an attacker find out which emails have accounts.

By default Spring folds both into BadCredentialsException and even hashes a dummy password when the user is missing so the timing matches. For debugging, read server-side logs at DEBUG. Registration and password-reset pages must answer neutrally too, or they leak the same information.

One application serves a web form UI and a mobile API. How do you organise Spring Security?

Two SecurityFilterChains: a stateless /api/** chain with bearer tokens, CSRF off and JSON 401s; and a form-login chain with sessions and CSRF on for the rest.

Declare the API chain first with securityMatcher("/api/**"), because FilterChainProxy stops at the first match. Each chain has its own entry point and error handling. Test both, especially that the API doesn’t quietly accept the session cookie (if it does, CSRF comes back).

Useful phrases for interviews

  • “Spring Security is a filter chain that runs before the DispatcherServlet.”
  • “FilterChainProxy picks the first SecurityFilterChain whose matcher fits the request.”
  • “I keep the principal small because it’s stored in the session.”
  • “DaoAuthenticationProvider loads the user and checks the password hash.”
  • “hasRole adds the ROLE_ prefix, hasAuthority compares the exact string.”
  • “The entry point redirects browsers to the login page and returns 401 to AJAX calls.”
  • “After login the user lands on the saved request instead of the home page.”
  • “Different error messages for unknown users enable user enumeration.”
  • “Since Security 6, forward dispatches are authorized too, so JSP views need a permit rule.”
  • “I end the rules with anyRequest().authenticated() so new endpoints aren’t open by accident.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.