Form login and HTTP Basic

formLogin() logs browsers in with a form: a generated page at /login, or your own. httpBasic() logs programs in with the Authorization: Basic header. Both check the name and password with the AuthenticationManager of spring_security_core, so the users come from your UserDetailsService bean.

Why

A web application for people needs a login page, a session after the login, and a logout. An API used by scripts needs a login with every request. The two mechanisms cover both, with the details done right: the session id changes at login, the failure reason is never shown, logout is a POST with a CSRF token.

Example

@Bean()
SecurityFilterChain filterChain(HttpSecurity http) => http
    .authorizeHttpRequests((auth) => auth
        .requestMatchers('/sign-in', '/assets/**').permitAll()
        .anyRequest().authenticated())
    .formLogin((form) => form
        .loginPage('/sign-in')                 // your page: the generated one is gone
        .defaultSuccessUrl('/dashboard')
        .failureUrl('/sign-in?error'))
    .httpBasic((basic) => basic.realmName('Library'))
    .logout((logout) => logout
        .logoutSuccessUrl('/sign-in?bye')
        .deleteCookies('SHOPSESSION'))
    .build();

Your page posts username, password and the CSRF token to the same path:

@GetMapping('/sign-in')
String signIn(ServerHttpRequest request) {
  final csrf = csrfTokenOf(request)!;
  return '''<form method="post" action="/sign-in">
    <input name="username"> <input name="password" type="password">
    <input type="hidden" name="${csrf.parameterName}" value="${csrf.token}">
    <button>Sign in</button></form>''';
}

Form login

Option Default Meaning
loginPage(url) the generated page at /login Your own page, served by a controller and reachable by everyone.
loginProcessingUrl(url) the login page's path Where the form posts.
usernameParameter(name) username The username field.
passwordParameter(name) password The password field.
defaultSuccessUrl(url, alwaysUse:) / Where the browser goes after a login when no page was saved before it; with alwaysUse: true, always.
failureUrl(url) the login page with ?error Where the browser goes after a failed login.
successHandler(handler) a redirect Answers a login another way, for example with JSON for a script.
failureHandler(handler) a redirect Answers a failed login another way.

What happens:

  1. A browser that must log in is redirected to the login page, and the page it wanted is saved (in a signed cookie, REDIRECT_URI).
  2. The form posts to the processing URL with the CSRF token. A form posted without the token is refused with 403.
  3. On success, the session gets a new id (session fixation protection), keeps the user, and the browser goes back to the saved page, else to defaultSuccessUrl. The saved page is used only when it is a path of this site.
  4. On failure, the browser goes to failureUrl. The page never says why: "Bad credentials" covers an unknown user, a wrong password and a locked account alike.

The generated page has the username and password fields and the CSRF token and, with oauth2Login(), a link per registration. With ?error it says "Bad credentials", with ?logout "You have been signed out".

A form or Basic login without any user in the application fails the startup.

HTTP Basic

Option Default Meaning
realmName(realm) Realm The realm of the WWW-Authenticate challenge, which browsers may show.
authenticationEntryPoint(entryPoint) the Basic challenge What a client that must log in gets.

Logout

Option Default Meaning
logoutUrl(url) /logout The logout path.
logoutSuccessUrl(url) the login page with ?logout Where the browser goes after the logout.
logoutSuccessHandler(handler) a redirect Answers the logout another way (for example OidcClientInitiatedLogoutSuccessHandler).
invalidateHttpSession(invalidate:) true Whether the session ends, with everything in it.
deleteCookies(name, ...) none Expires up to three cookies.
addLogoutHandler(handler) Runs before the built-in handlers.
disable() Removes the logout endpoint.

While CSRF protection is on, only POST logs out: a GET could be triggered by a link or an image on another site. GET /logout then shows a confirmation page with a button that posts the logout with the CSRF token, when form login uses the generated page. With CSRF off, GET, POST, PUT and DELETE all log out. A logout publishes LogoutSuccessEvent for a user who was logged in.

The default user

Without users of your own, the starter makes one from properties:

Property Default Meaning
spring.security.user.name user The name.
spring.security.user.password a random one, logged at startup The password, for development only.
spring.security.user.roles none The roles, without ROLE_.

Users for one chain

http.userDetailsService(service) or http.authenticationManager(manager) gives a chain its own users. Such users never get their old password hashes upgraded at login; users of a UserDetailsService bean do.

In Spring (Java)

http.formLogin(form -> form.loginPage("/sign-in").defaultSuccessUrl("/dashboard"))
    .httpBasic(basic -> basic.realmName("Library"));

The options are Spring's. Not here yet: rememberMe(), oneTimeTokenLogin(), passkeys, x509(), switch user.

See also