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
- 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}. Withoauth2ResourceServertoo, programs asking for JSON get a401instead, which a Flutter web app turns into a navigation to/oauth2/authorization/keycloak. /oauth2/authorization/{registrationId}keeps a new authorization request (a randomstate, a PKCE verifier, an OpenID Connectnonce) in a signed cookie and redirects to the provider. An unknown registration is a400.- The provider redirects back to
/login/oauth2/code/{registrationId}. The saved request is taken by itsstateand removed (a callback works once); a callback without one, with anotherstate, or for another registration fails. Anerrorfrom the provider fails, and so does anissparameter (RFC 9207) of another issuer. - 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 andnonce. The user info is loaded; itssubmust be the ID token's. The authorities (OIDC_USER,SCOPE_*) go through theGrantedAuthoritiesMapperbean, if any. - 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 todefaultSuccessUrl(/). 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
- The session cookie must reach the callback, a top-level redirect from the provider: keep it
SameSite=Lax(the default), notStrict. - A Flutter web app and the server must be on the same site (
localhostwith two ports,app.example.comandapi.example.com), and the app's requests must send cookies (credentials: 'include') and the CSRF token onPOST,PUTandDELETE.
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
- The callback takes the response from the body of a
POST(at most 64 KB) with the same checks. AGETfor a form post login, aPOSTfor a query login, or a response split between the query and the body fails (invalid_request) and leaves the login in progress alone. - The callback's
POSTis exempt from CSRF; thestate, bound to the browser by the signed cookie, protects it. - The provider's post is cross-site, which carries only
SameSite=None; Securecookies: the authorization request cookie is made so over HTTPS. Over plain HTTP the login fails, closed, with a warning in the log. After a form post login the user lands on the default page.
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.
- Roles: Google sends none. Give them in a
GrantedAuthoritiesMapperbean:
@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'),
];
}
- Keep users by
sub, never by e-mail: an address can change owner, and another provider may send one it never verified. Use the e-mail only withemail_verified=true. - Refresh tokens are not rotated: keep it safe and revoke it when the user logs out or deletes the account.
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.
- The client secret is a JWT signed ES256 with that key, made per request from the
client-secret-jwt.*properties (one hour by default, cached until a tenth of it is left). The key is never logged. - Name and e-mail come once, on the first login, in the posted
user(userRequest.additionalParameters['user']of yourOidcUserService): store them then. It is not signed: never decide who the user is by it. - Over HTTPS only: Apple posts the response back (form post).
- Revoke the user's tokens when they delete their account, as the App Store requires.
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()).