Single sign-on

With oauth2Login(), users log in at an identity provider (Keycloak, Google, GitHub, Auth0, Okta, Apple...) instead of with a password of the application. The browser is sent to the provider's login page and comes back logged in. This is OAuth 2.0's authorization code flow, with PKCE, and OpenID Connect when the provider has it. The server is the client and keeps the tokens.

Why

The provider handles passwords, multi-factor login and account recovery; the application never sees a password. Use it for pages rendered by the server, and for a Flutter web app: the server is the app's backend (BFF), keeps the tokens, and the browser holds only the HttpOnly session cookie, which no injected script can read. A web page has no safe place for tokens, so it never gets them. Native apps log in themselves and send their access token; a chain can accept both.

Example

Configure a registration, as in Spring Boot, and the default chain logs browsers in through it:

spring.security.oauth2.client.registration.keycloak.client-id=neon-web
spring.security.oauth2.client.registration.keycloak.client-secret=${KEYCLOAK_SECRET}
spring.security.oauth2.client.registration.keycloak.scope=openid,profile,email
spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8180/realms/neon

The provider must accept the redirect URI {baseUrl}/login/oauth2/code/{registrationId} (http://localhost:8080/login/oauth2/code/keycloak). The registration properties belong to spring_boot_starter_oauth2_client.

Or in a chain of your own:

@Bean()
SecurityFilterChain web(HttpSecurity http, ClientRegistrationRepository registrations) => http
    .authorizeHttpRequests((auth) => auth
        .requestMatchers('/', '/public/**').permitAll()
        .anyRequest().authenticated())
    .oauth2Login((login) => login
        // The Flutter web app, served from another port of the same site.
        .defaultSuccessUrl('http://localhost:5050/', alwaysUse: true))
    // Native apps send the provider's access tokens.
    .oauth2ResourceServer((server) => server.jwt())
    // Logging out ends the session at the provider too.
    .logout((logout) => logout.logoutSuccessHandler(
        OidcClientInitiatedLogoutSuccessHandler(
          registrations,
          postLogoutRedirectUri: '{baseUrl}/',
        )))
    .build();

@RestController()
class MeController {
  @GetMapping('/api/me')
  Map<String, Object?> me(@AuthenticationPrincipal() OidcUser user) =>
      {'name': user.fullName, 'email': user.email};
}

What happens

  1. A browser that must log in goes to the generated login page, which lists the registrations; with exactly one (and no form login) it goes straight to /oauth2/authorization/{registrationId}. With oauth2ResourceServer too, programs asking for JSON get a 401 instead, which a Flutter web app turns into a navigation to /oauth2/authorization/keycloak.
  2. /oauth2/authorization/{registrationId} keeps a new authorization request (a random state, a PKCE verifier, an OpenID Connect nonce) in a signed cookie and redirects to the provider. An unknown registration is a 400.
  3. The provider redirects back to /login/oauth2/code/{registrationId}. The saved request is taken by its state and removed (a callback works once); a callback without one, with another state, or for another registration fails. An error from the provider fails, and so does an iss parameter (RFC 9207) of another issuer.
  4. The code is exchanged at the token endpoint with the PKCE verifier and the exact redirect URI. The ID token's signature is checked with the provider's keys, then its issuer, audience, azp, expiry and nonce. The user info is loaded; its sub must be the ID token's. The authorities (OIDC_USER, SCOPE_*) go through the GrantedAuthoritiesMapper bean, if any.
  5. The session gets a new id, keeps the user and the tokens (the OAuth2AuthorizedClientRepository), and the browser goes back to the page it wanted, else to defaultSuccessUrl (/). That URL is configuration: nothing in the request can send the browser elsewhere. A failure goes to /login?error, without its reason.

Options

oauth2Login option Default
loginPage(url) the generated page at /login
defaultSuccessUrl(url, alwaysUse:) /; the saved page first
failureUrl(url), successHandler(h), failureHandler(h) /login?error; redirects
authorizationEndpoint: baseUri, authorizationRequestRepository, authorizationRequestResolver /oauth2/authorization, a signed cookie, DefaultOAuth2AuthorizationRequestResolver
redirectionEndpoint: baseUri (or loginProcessingUrl) /login/oauth2/code/*
tokenEndpoint: accessTokenResponseClient the bean, else one over the HttpTransport
userInfoEndpoint: userService, oidcUserService, userAuthoritiesMapper the beans, else DefaultOAuth2UserService, OidcUserService, none
clientRegistrationRepository, authorizedClientRepository, authorizedClientService the beans
idTokenDecoder the OidcIdTokenDecoder bean, else an OidcIdTokenDecoderFactory (signatures checked)

A controller gets the user as @AuthenticationPrincipal() OAuth2User user (an OidcUser with OpenID Connect), and the tokens from the OAuth2AuthorizedClientRepository bean.

Cookies and sites

Responses as a form post

With response-mode=form_post on a registration (the default of the apple provider), the provider's page posts code and state to the callback as a form, so they never appear in a URL, a log or the history:

spring.security.oauth2.client.registration.keycloak.response-mode=form_post

Login with Google

spring.security.oauth2.client.registration.google.client-id=123-abc.apps.googleusercontent.com
spring.security.oauth2.client.registration.google.client-secret=${GOOGLE_SECRET}

The google registration gets its endpoints from CommonOAuth2Provider (scopes openid profile email). In Google Cloud, create a Web application client with the redirect URI https://<your server>/login/oauth2/code/google.

@Component()
class Admins implements GrantedAuthoritiesMapper {
  Admins(this._users);
  final UserRepository _users;

  @override
  List<GrantedAuthority> mapAuthorities(Iterable<GrantedAuthority> authorities) => [
        ...authorities,
        for (final authority in authorities)
          if (authority is OidcUserAuthority && _users.isAdmin(authority.idToken.subject))
            SimpleGrantedAuthority('ROLE_ADMIN'),
      ];
}

Sign in with Apple

spring.security.oauth2.client.registration.apple.client-id=books.neon.web
spring.security.oauth2.client.registration.apple.client-authentication-method=client_secret_post
spring.security.oauth2.client.registration.apple.client-secret-jwt.issuer=ABCDE12345
spring.security.oauth2.client.registration.apple.client-secret-jwt.key-id=XYZ987KEY1
spring.security.oauth2.client.registration.apple.client-secret-jwt.private-key-location=file:/run/secrets/AuthKey_XYZ987KEY1.p8

The apple registration (an addition: Spring has none) has Apple's endpoints, the scopes openid name email, client_secret_post, no user-info endpoint and response-mode=form_post. In the Apple Developer account you need a Services ID (the client id) with the return URL https://<your server>/login/oauth2/code/apple (Apple accepts neither localhost nor an IP), a key with Sign in with Apple (the .p8 file and its key id), and the team id.

Logout at the provider

OidcClientInitiatedLogoutSuccessHandler(registrations, postLogoutRedirectUri: '{baseUrl}/') ends the session here, then sends the browser to the provider's end_session_endpoint with the ID token, so the user is logged out there too.

In Spring (Java)

http.oauth2Login(login -> login.defaultSuccessUrl("http://localhost:5050/", true));

Compared with Spring Security 7.1 by a differential test (the same browser steps against the same fake provider), the outcomes match, except where this starter is stricter: a redirect back whose iss is not the issuer, or to another registration's callback, fails here (Spring logs the user in); an unknown registration is a 400 (Spring: 500); a failed login creates no session. ID token signatures are always checked. The apple provider, response-mode and the JWT client secret are additions. Not here yet: oauth2Client(), @RegisteredOAuth2AuthorizedClient, back-channel logout (oidcLogout()).

See also