OAuth2 Login in Spring Security
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
- An anonymous user asks for a protected page. Spring Security saves the request and redirects to
/oauth2/authorization/google. OAuth2AuthorizationRequestRedirectFilterbuilds the provider URL with yourclient_id, the scopes, aredirect_uri, randomstateandnoncevalues, and a PKCEcode_challenge, and remembers them in the session.- The user signs in at Google, which redirects the browser back to
/login/oauth2/code/googlewith an authorization code and the samestate. OAuth2LoginAuthenticationFilterrejects the callback if thestatedoes not match. Otherwise it exchanges the code for tokens in a direct server-to-server call authenticated with your client secret, sending the PKCEcode_verifierthat matches the earlier challenge.- The ID token's signature, issuer, audience, expiry and
nonceare validated, anOidcUseris created, the session ID is changed and the user returns to the saved page.
4. Key Configuration and Classes
| Item | Purpose |
|---|---|
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 / OAuth2User | The logged-in principal with the ID token claims or user-info attributes |
OAuth2AuthorizedClientService | Stores 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:
<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
package com.javabytechie.recipes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/error").permitAll()
.anyRequest().authenticated())
.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout.logoutSuccessUrl("/"));
return http.build();
}
}
package com.javabytechie.recipes;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RecipeController {
@GetMapping("/")
public String home() {
return "Welcome to Spice Route recipes. Sign in to save your favourites.";
}
@GetMapping("/my-recipes")
public Map<String, Object> myRecipes(@AuthenticationPrincipal OidcUser user) {
return Map.of(
"name", user.getFullName(),
"email", user.getEmail(),
"googleSubject", user.getSubject(), // stable user ID at Google
"saved", List.of("Kerala fish curry", "Bajra roti"));
}
}
package com.javabytechie.recipes;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RecipeApplication {
public static void main(String[] args) {
SpringApplication.run(RecipeApplication.class, args);
}
}
6. Step-by-Step Code Explanation
- Registration by properties. Because
googleis a provider Spring Security knows, only the client ID, secret and scopes are needed; endpoints and key locations are filled in automatically. Requesting theopenidscope switches on OpenID Connect. 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.OidcUserexposes the validated ID token claims:getFullName(),getEmail()andgetSubject(). Use the subject (with the issuer) as the stable key for your own user records; email addresses can change.- 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:
$ 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
| Advantages | Limitations |
|---|---|
| No password storage or reset flows in your app | Depends on the provider being available |
| Strong security (MFA, anomaly detection) from the provider | Users without an account at that provider need another way in |
| State, nonce and token validation handled by Spring Security | Logging out of your app does not log the user out of the provider |
| Several providers with almost no extra code | Profile data differs per provider; map it into your own user model |
9. Common Mistakes and Best Practices
redirect_uri_mismatchat 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=frameworkso Spring builds HTTPS URLs fromX-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(orOAuth2Userfor non-OIDC providers). - Keep secrets out of code, register exact redirect URIs and map external users to your own roles.
11. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between OAuth2 Login and OAuth2 resource server?
With OAuth2 Login, your application is a client that signs users in through a provider and keeps them in a session. A resource server is an API that validates access tokens sent by clients.
Q2. Is OAuth2 Login the same as OpenID Connect?
When the openid scope is requested, yes: Spring Security performs OpenID Connect and validates an ID token. For plain OAuth2 providers such as GitHub, it reads the user from a user-info endpoint instead.
Q3. What is the state parameter for?
It links the callback to the authorization request that your application started. Spring Security rejects callbacks whose state does not match, which prevents attackers from injecting their own authorization codes.
Q4. How do I get the logged-in user's email with OAuth2 Login?
Request the email scope and inject @AuthenticationPrincipal OidcUser user; then call user.getEmail().
Q5. Can I use several providers at the same time?
Yes. Add one registration per provider. Spring Security then shows a generated login page listing each provider, or you can build your own page with links to /oauth2/authorization/{registrationId}.