As a next step after implementing your own JWT-based authentication, you’ll likely want to allow users to sign in with their Google account. With Spring Security OAuth2 Client, you can achieve Google social login with surprisingly little code.
This article walks through the entire process — from creating an OAuth2 client in Google Cloud Console, to configuring application.yml, setting up SecurityFilterChain, and retrieving user information — all while running locally.
Overview of the OAuth2 Authorization Code Flow
Before diving into the implementation, let’s understand the authorization code flow.
1. Browser → Spring Boot: Access /oauth2/authorization/google
2. Spring Boot → Browser: Redirect to Google's authorization endpoint
3. Browser → Google: User logs in and grants permissions
4. Google → Spring Boot: Returns authorization code (code) to the redirect URI
5. Spring Boot → Google: Exchanges code for an access token (back channel)
6. Spring Boot → Google: Retrieves user info from the UserInfo endpoint
7. Spring Boot: Saves user info to the session and completes login
The key difference from issuing your own JWTs is that Spring Security handles steps 5–7 almost automatically. You don’t need to write the token exchange request yourself.
Creating an OAuth2 Client in Google Cloud Console
First, obtain your client-id and client-secret.
- Create a project in Google Cloud Console
- Go to “APIs & Services” → “OAuth consent screen” and configure it (for testing, “External” is fine)
- Go to “Credentials” → Create an “OAuth Client ID”
- Select “Web application” as the application type
- Add
http://localhost:8080/login/oauth2/code/googleto the authorized redirect URIs
- Note down the displayed
client-idandclient-secret
The redirect URI path /login/oauth2/code/google is the default value for Spring Security OAuth2 Client. It’s easiest to use this as-is at first.
Project Setup
Add spring-boot-starter-oauth2-client to your dependencies.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
}
This starter includes spring-security-oauth2-client and spring-security-oauth2-jose (for ID token validation).
Configuring OAuth2 Settings in application.yml
Add the following to your application.yml.
spring:
security:
oauth2:
client:
registration:
google:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
scope:
- openid
- email
- profile
Including openid in the scope causes the response to be treated as an OidcUser, making it easy to extract the email address and name. You don’t need to define a provider — Spring Boot automatically resolves Google’s authentication endpoints.
Always store client-id and client-secret in environment variables. It’s easy to accidentally hardcode them in source code and push them to Git, so be careful.
Enabling oauth2Login() in SecurityFilterChain
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.defaultSuccessUrl("/dashboard", true)
);
return http.build();
}
}
Simply calling oauth2Login() enables Google login. Use defaultSuccessUrl to specify where to redirect after a successful login.
Leave CSRF enabled by default. The OAuth2 flow has built-in CSRF protection via the state parameter, which Spring Security handles automatically.
Retrieving User Information After Login
Use @AuthenticationPrincipal in your controller to receive user information.
@RestController
public class UserController {
@GetMapping("/dashboard")
public Map<String, Object> dashboard(@AuthenticationPrincipal OidcUser user) {
return Map.of(
"name", user.getAttribute("name"),
"email", user.getAttribute("email"),
"picture", user.getAttribute("picture")
);
}
}
Since we included the openid scope, we can cast to OidcUser. Without openid, it becomes OAuth2User. In places where @AuthenticationPrincipal is not available — such as the service layer — you can retrieve it via SecurityContextHolder.getContext().getAuthentication().
Customizing Post-Login Behavior
A common requirement is saving user information to a database on first login. In that case, implement AuthenticationSuccessHandler.
@Component
public class OAuth2LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private final UserService userService;
public OAuth2LoginSuccessHandler(UserService userService) {
super("/dashboard");
this.userService = userService;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
OidcUser oidcUser = (OidcUser) authentication.getPrincipal();
userService.saveOrUpdate(oidcUser.getEmail(), oidcUser.getAttribute("name"));
super.onAuthenticationSuccess(request, response, authentication);
}
}
Register it in SecurityConfig with .oauth2Login(oauth2 -> oauth2.successHandler(successHandler)).
Session-Based Authentication vs. JWT
This implementation is session-based. Spring Security OAuth2 Client stores the OAuth2AuthorizedClient in the HttpSession by default.
If you need to scale out across multiple servers, you’ll need session sharing (e.g., Redis). For a stateless API, a common architecture is to issue your own JWT after completing the authorization code flow. See Implementing Stateless Authentication with Spring Security + JWT for that approach.
Verification
Start the application and navigate to http://localhost:8080. Spring Security’s default login page will appear. Click the “Sign in with Google” link to be redirected to Google’s authentication screen, and after logging in you’ll be returned to /dashboard.
If you see a redirect_uri_mismatch error, verify that the redirect URI in Google Cloud Console is set to http://localhost:8080/login/oauth2/code/google. If you get a 403 error, review the permitAll() settings in your SecurityFilterChain.
Adding support for other providers is equally straightforward. Simply add a github key to registration and it will work. Spring Boot supports GitHub, Facebook, Okta, and others out of the box.
Summary
Google login with Spring Security OAuth2 Client is essentially up and running with just a dependency addition, an application.yml configuration, and a single oauth2Login() call. The amount of code required is remarkably small given the complexity of the underlying flow.
For a comparison with Basic authentication or JWT, check out How to Implement Basic Authentication in Spring Boot and How to Implement Stateless Authentication with JWT. When integrating with a frontend, Spring Boot CORS Configuration Guide is also a helpful reference.