00:00

OAuth2 Login in Spring Security

Last updated:

OAuth2 Login lets users sign in to your application with an account they already have at Google, Microsoft, GitHub, Okta or any OpenID Connect provider. Your application never sees or stores their password. Instead, the provider authenticates the user and sends your application a short-lived code, which Spring Security exchanges for tokens that identify the user.

This tutorial adds "Sign in with Google" to a recipe-sharing site with Spring Boot. It explains each step of the authorization code flow, shows the user information Spring Security provides, and verifies the parts of the flow that run inside your application, including the protection against forged callbacks.

1. What Is OAuth2 Login?

Despite its name, OAuth2 Login is mostly OpenID Connect (OIDC) login. OAuth2 on its own only grants access to APIs; OIDC adds an ID token, a signed JWT that tells your application who the user is. Spring Security's oauth2Login() runs the authorization code flow, validates the ID token, and creates an authenticated OidcUser principal. For providers without OIDC, such as GitHub, it calls the provider's user-info endpoint and creates an OAuth2User instead.

Here your application is the OAuth2 client, not the resource server. If you need to protect an API with tokens from such a provider, see OAuth2 resource server with JWT.

2. Why Use OAuth2 Login?

  • No passwords to store. Password storage, reset, MFA and account recovery are the provider's responsibility.
  • Fewer steps for users. One click with an account they already trust.
  • Single sign-on. In companies, the same provider (for example Entra ID or Okta) signs users into many applications.
  • Standard and secure flow. Spring Security implements state, nonce and PKCE handling, and ID token validation for you.

3. How the Authorization Code Flow Works

OAuth2 Login authorization code flowThe browser requests a protected page and is redirected to /oauth2/authorization/google, then to Google with client_id, scope, state, nonce and redirect_uri. After the user signs in, Google redirects back to /login/oauth2/code/google with a code. Spring Security checks the state, exchanges the code for tokens on a back channel, validates the ID token and creates the session. 1. Browser GET /my-recipes 2. /oauth2/authorization/google save request, create state and nonce 3. Google sign-in page user authenticates, consents 4. /login/oauth2/code/google ?code=...&state=... 5. Back channel code for ID and access tokens ID token validated 6. Logged in OidcUser in session
Figure 1: the browser carries redirects; the code-for-token exchange happens server to server.
  1. An anonymous user asks for a protected page. Spring Security saves the request and redirects to /oauth2/authorization/google.
  2. OAuth2AuthorizationRequestRedirectFilter builds the provider URL with your client_id, the scopes, a redirect_uri, random state and nonce values, and a PKCE code_challenge, and remembers them in the session.
  3. The user signs in at Google, which redirects the browser back to /login/oauth2/code/google with an authorization code and the same state.
  4. OAuth2LoginAuthenticationFilter rejects the callback if the state does not match. Otherwise it exchanges the code for tokens in a direct server-to-server call authenticated with your client secret, sending the PKCE code_verifier that matches the earlier challenge.
  5. The ID token's signature, issuer, audience, expiry and nonce are validated, an OidcUser is created, the session ID is changed and the user returns to the saved page.

4. Key Configuration and Classes

ItemPurpose
spring.security.oauth2.client.registration.<id>.*Client ID, secret, scopes and redirect URI for one provider
spring.security.oauth2.client.provider.<id>.*Provider endpoints; not needed for Google, GitHub, Facebook and Okta, which Spring knows already
oauth2Login()Adds the redirect and callback filters and a default login page listing providers
OidcUser / OAuth2UserThe logged-in principal with the ID token claims or user-info attributes
OAuth2AuthorizedClientServiceStores the access token if you also need to call the provider's APIs

5. A Complete Example: Sign In with Google on a Recipe Site

The home page is public; "My recipes" requires sign-in with Google. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2 and the OAuth2 client starter:

pom.xml (dependencies)
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security-oauth2-client</artifactId>
</dependency>

First, create an OAuth client in the Google Cloud console (APIs and Services, Credentials, "OAuth client ID", type "Web application") and add http://localhost:8080/login/oauth2/code/google as an authorised redirect URI. Keep the client ID and secret out of source code, for example in environment variables:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: ${GOOGLE_CLIENT_ID}
            client-secret: ${GOOGLE_CLIENT_SECRET}
            scope: openid,profile,email

6. Step-by-Step Code Explanation

  1. Registration by properties. Because google is a provider Spring Security knows, only the client ID, secret and scopes are needed; endpoints and key locations are filled in automatically. Requesting the openid scope switches on OpenID Connect.
  2. oauth2Login(Customizer.withDefaults()) adds the two filters for the redirect and the callback. With a single registration, unauthenticated users are sent straight to that provider; with several, Spring shows a page listing them at /login.
  3. OidcUser exposes the validated ID token claims: getFullName(), getEmail() and getSubject(). Use the subject (with the issuer) as the stable key for your own user records; email addresses can change.
  4. Logout ends the session in your application only. The user stays signed in at Google; for a full single sign-out with providers that support it, look at OidcClientInitiatedLogoutSuccessHandler.

7. Expected Output

A full sign-in needs a real Google account in a browser, so it cannot be scripted here. The requests below exercise everything that happens inside the application. They were run with a placeholder client ID, demo-client-id.apps.googleusercontent.com:

Terminal
$ curl localhost:8080/
HTTP/1.1 200
Welcome to Spice Route recipes. Sign in to save your favourites.

$ curl -c cookies.txt localhost:8080/my-recipes
HTTP/1.1 302
Location: http://localhost:8080/oauth2/authorization/google

$ curl -b cookies.txt -c cookies.txt localhost:8080/oauth2/authorization/google
HTTP/1.1 302
Location: https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=demo-client-id.apps.googleusercontent.com&scope=openid%20profile%20email&state=RAFVuPZTQTBXybQCbUpAR_S638uknfRx1HRdmAxxyoU%3D&redirect_uri=http://localhost:8080/login/oauth2/code/google&nonce=eDq6u3IMaictfta8mf8wiadT6V1n7zjS0dP3ts6QzpQ&code_challenge=oevw0V97DDIrr2klQU3aLvl4KuaiOZ-BDWiVKBeIAFQ&code_challenge_method=S256

$ curl -b cookies.txt 'localhost:8080/login/oauth2/code/google?code=forged-code&state=forged-state'
HTTP/1.1 302
Location: http://localhost:8080/login?error

The home page is public. "My recipes" redirects to /oauth2/authorization/google, which in turn redirects to Google's authorization endpoint with the client ID, the requested scopes, a random state, the callback URL, a random nonce and a PKCE code_challenge (S256). PKCE binds the later code exchange to this request, so a stolen authorization code is useless on its own; Spring Security 7.1.2 sends it here even though this client also has a secret. The last request imitates an attacker posting a code to the callback with a made-up state: Spring Security finds no matching authorization request and sends the browser to /login?error without ever contacting Google. After a real sign-in, /my-recipes returns the user's name, email and Google subject from the ID token.

8. Advantages and Limitations

AdvantagesLimitations
No password storage or reset flows in your appDepends on the provider being available
Strong security (MFA, anomaly detection) from the providerUsers without an account at that provider need another way in
State, nonce and token validation handled by Spring SecurityLogging out of your app does not log the user out of the provider
Several providers with almost no extra codeProfile data differs per provider; map it into your own user model

9. Common Mistakes and Best Practices

  • redirect_uri_mismatch at Google. The redirect URI registered at the provider must match exactly, including scheme, host, port and path.
  • Secrets in Git. Use environment variables or a secrets manager for the client secret.
  • Using email as the user key. Store the provider's subject and issuer; emails can change or be reused.
  • Behind a proxy, wrong redirect URLs. Set server.forward-headers-strategy=framework so Spring builds HTTPS URLs from X-Forwarded-* headers.
  • Treating "logged in with Google" as authorised. Map users to your own roles, for example with a custom OidcUserService, before granting access to sensitive features.

10. Summary

  • OAuth2 Login signs users in through an external provider using the authorization code flow, usually with OpenID Connect.
  • With Spring Boot, add the OAuth2 client starter, configure a registration and call oauth2Login().
  • Spring Security handles redirects, state, nonce, the code-for-token exchange and ID token validation.
  • Controllers read the user from OidcUser (or OAuth2User for non-OIDC providers).
  • Keep secrets out of code, register exact redirect URIs and map external users to your own roles.

11. References