Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Authentication Mechanisms

Form Login and Logout in Spring Security

Configure formLogin with a custom page, success and failure handlers, understand the session cookie flow, and set up a safe POST-based logout.

Form login is the mechanism most people meet first: a page with a username and password, a session cookie afterward, and a logout button. Spring Security generates a default page, but a real application replaces it with its own. This lesson explains what happens between the submit button and the cookie, how to customize every step, and how logout really works.

The real configuration is shown as read-only Java. The runnable examples are small stand-ins that model the session cookie flow, because a servlet container is not available on this site.

What formLogin adds

Java
http.formLogin(Customizer.withDefaults());

This registers UsernamePasswordAuthenticationFilter, which watches for POST /login, reads the username and password parameters, builds an unauthenticated UsernamePasswordAuthenticationToken and hands it to the AuthenticationManager (see core concepts). It also adds a generated login page at GET /login and a DefaultLoginPageGeneratingFilter. Replace the page with your own:

Java
http
    .authorizeHttpRequests(a -> a
        .requestMatchers("/login", "/css/**").permitAll()
        .anyRequest().authenticated())
    .formLogin(f -> f
        .loginPage("/login")                 // GET: your Thymeleaf/Blade/Mustache page
        .loginProcessingUrl("/login")        // POST: handled by the filter, not a controller
        .defaultSuccessUrl("/dashboard", false)
        .failureUrl("/login?error")
        .usernameParameter("email")
        .permitAll());

Points that trip beginners:

  • loginPage must be reachable without authentication, so permit it, or you create a redirect loop. permitAll() inside formLogin does this for the login URLs.
  • You do not write a controller for the POST. The filter handles it. Your controller only returns the page for GET /login.
  • The form must include the CSRF token (Thymeleaf adds it automatically; in other engines add a hidden _csrf field). See CSRF protection.

A minimal matching form:

HTML
<form method="post" action="/login">
  <input type="hidden" name="_csrf" value="${csrf.token}">
  <input name="email" type="email" required>
  <input name="password" type="password" required>
  <button>Sign in</button>
</form>

The flow from POST to cookie

sequenceDiagram
    participant B as Browser
    participant F as UsernamePasswordAuthenticationFilter
    participant M as AuthenticationManager
    participant S as Session store
    B->>F: POST /login (email, password, _csrf)
    F->>M: authenticate(token)
    M-->>F: Authentication (authenticated)
    F->>S: new session id, save SecurityContext
    F-->>B: 302 to saved request + Set-Cookie JSESSIONID
    B->>F: GET /dashboard (Cookie: JSESSIONID)
    Note over F,S: SecurityContext is loaded from the session

After a successful login, the identity lives on the server in the session; the browser only holds an opaque id.

Two details deserve attention. First, session fixation protection: on success Spring Security issues a new session id (changeSessionId), so an attacker who planted a known id before the login gains nothing. Second, the saved request: when an anonymous visitor asks for /reports, the RequestCache remembers that URL, sends the visitor to /login, and after success redirects back. defaultSuccessUrl("/dashboard", false) uses /dashboard only when nothing was saved; passing true always forces it.

A session login you can run

The stand-in below models a session store, a login that rotates the session id, and a protected page that reads the identity back from the cookie.

Java Form login with session id rotation (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.

The planted id gets nothing because login issues a fresh id. That is what sessionFixation().changeSessionId() (the default) does.

Success and failure handlers

For single-page applications that post the form with fetch, a redirect is awkward. Replace it with handlers that return JSON:

Java
.formLogin(f -> f
    .successHandler((req, res, auth) -> {
        res.setStatus(200);
        res.setContentType("application/json");
        res.getWriter().write("{\"user\":\"" + auth.getName() + "\"}");
    })
    .failureHandler((req, res, ex) -> {
        res.setStatus(401);
        res.setContentType("application/json");
        res.getWriter().write("{\"error\":\"bad_credentials\"}");
    }))

Do not echo ex.getMessage() blindly. The default messages distinguish "bad credentials" from "user disabled" and "account locked", which is useful to an attacker who is probing usernames. For a public login, show one message ("Invalid email or password") and log the cause. Spring Security already hides whether the username exists by hashing a dummy password when the user is missing, which equalizes timing.

Logout

Logout is a feature, not just a button. The default:

Java
http.logout(l -> l
    .logoutUrl("/logout")                    // POST by default (CSRF protected)
    .logoutSuccessUrl("/login?logout")
    .invalidateHttpSession(true)
    .deleteCookies("JSESSIONID")
    .clearAuthentication(true));

LogoutFilter runs a list of LogoutHandlers (clear the SecurityContext, invalidate the session, remove cookies) and then a LogoutSuccessHandler (redirect or status). Logout is a POST with a CSRF token on purpose: a GET /logout can be triggered by an <img src="/logout"> on any page, signing users out against their will. If you must use GET, you accept that risk deliberately with logoutRequestMatcher.

The second runnable example adds logout and the "remove everything" idea: after logout the old cookie must stop working on the server, which is the whole point of server-side sessions.

Java Logout invalidates the server-side session (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.

With JWTs there is no server-side session to delete, so logout means "forget the token on the client and let it expire". That limitation is the subject of refresh tokens and revocation.

Setting Purpose
sessionManagement(s -> s.maximumSessions(1)) Limit concurrent logins per user
rememberMe(...) Long-lived login cookie, see remember-me
requestCache(...) Control which request is remembered for the post-login redirect
securityContext(...) Where the context is saved (default: HTTP session)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who handles POST /login in a standard formLogin setup?

    The filter intercepts the login POST before MVC. Your controller only serves the GET page.
  2. 2. Why does Spring Security issue a new session id after a successful login?

    If an attacker planted a known id before login, rotating it makes that id worthless.
  3. 3. Why is the default logout a POST request?

    State-changing actions should not use GET. Logout is protected by the CSRF token like any other POST.
  4. 4. What does defaultSuccessUrl("/dashboard", false) do?

    The boolean alwaysUse is false, so a saved request wins over the default URL.

Summary

  • formLogin adds UsernamePasswordAuthenticationFilter; you supply the GET page and the filter handles the POST.
  • A successful login creates a new session id and stores the SecurityContext in it; the browser keeps only the cookie.
  • Use handlers for JSON responses in SPAs and keep failure messages generic.
  • Logout is a protected POST that clears the context, invalidates the session and deletes cookies.
  • Permit the login page itself and include the CSRF token in the form.

Next: HTTP Basic and stateless authentication