Implementing Google OAuth2 Login with Spring Security
Google sign-in gives a Spring Boot application a familiar authentication flow without requiring users to create another password. With Spring Security’s OAuth2 client support, your application redirects a user to Google, receives an authorisation code, and exchanges it for verified profile information.
This approach suits customer portals, booking systems, SaaS products, and internal tools used by Australian organisations. A Melbourne retailer, a Brisbane consultancy, or a Sydney start-up can offer a fast login experience while keeping passwords and account recovery outside the application.
The implementation below uses Spring Boot 3, Spring Security 6, and Google as the OpenID Connect provider. The same design can later support Microsoft, GitHub, or other identity providers with provider-specific configuration.
Registering An Application With Google
Open the Google Cloud Console and create a project for the application. Under APIs and Services, configure the OAuth consent screen, choose an external audience when appropriate, and add the scopes openid, profile, and email. For a production Australian business, use a verified company domain and explain clearly why profile information is collected.
Create an OAuth client under Credentials and select Web application. During local development, add this redirect URI:
http://localhost:8080/login/oauth2/code/google
For production, use the exact HTTPS address exposed by your application, such as:
https://portal.example.com/login/oauth2/code/google
Google compares redirect URIs strictly, so differences in ports, paths, or trailing slashes can produce a redirect_uri_mismatch error.
Adding Spring Boot OAuth2 Dependencies
Add the OAuth2 client starter to Maven. Spring Security supplies the login filter, authorisation request handling, token exchange, and OpenID Connect user service.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Store the client ID and secret outside source control. Environment variables work well in local development, Docker, and Australian cloud deployments hosted in Sydney or Melbourne regions.
spring:
security:
oauth2:
client:
registration:
google:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
scope:
- openid
- profile
- email
Because google is a recognised provider, Spring Boot automatically discovers Google’s authorisation, token, and user-information endpoints. Users will start the flow at /oauth2/authorization/google.
Configuring The Security Filter Chain
Define a SecurityFilterChain bean and enable OAuth2 login. Public pages can remain accessible, while application pages require an authenticated session.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/css/**", "/error").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout
.logoutSuccessUrl("/")
);
return http.build();
}
}
After successful authentication, Spring Security places the authenticated principal in the security context. A controller can read the Google profile using OidcUser, including the subject identifier, name, email, and profile image.
| Requirement | Recommended Spring Security feature | Practical result |
|---|---|---|
| Start Google login | /oauth2/authorization/google |
Redirects the browser to Google |
| Process the callback | OAuth2 login filter | Exchanges the authorisation code |
| Read profile details | OidcUser |
Provides claims such as email and name |
| Protect application pages | authenticated() |
Blocks anonymous requests |
| Sign out locally | Logout support | Clears the application session |
Do not use the email address as the only permanent identity key. Store Google’s stable sub claim together with the provider name. Email addresses can change, while the provider subject is intended to remain stable for that Google account.
Connecting OAuth2 Users To Your Database
The default login flow keeps the user in the session, but most business applications need a local account record. Implement OidcUserService or an authentication success handler to find or create a user after Google authentication.
A typical record includes provider, providerUserId, email, displayName, createdAt, and lastLoginAt. Keep authorisation roles in your database rather than trusting arbitrary profile fields. This lets an administrator grant roles such as CUSTOMER, STAFF, or ADMIN safely.
Useful account rules for a production application include:
- Normalise email addresses for display and matching.
- Save only profile data required by the application.
- Link an existing account through a deliberate verification flow.
- Record login events without storing access tokens unnecessarily.
- Respect Australian Privacy Act obligations and publish a clear privacy notice.
If the application calls Google APIs after login, request only the additional scopes required. A sign-in feature generally needs less permission than a calendar, Drive, or Gmail integration.
Testing And Operating The Login Flow
Run the application and visit /oauth2/authorization/google. Google should display the consent screen, then redirect to the callback endpoint. Check that the authenticated page displays the expected claims and that logout clears the local session.
Test both a new account and a returning account. Also test a Google Workspace account, a personal Gmail account, a denied consent request, and a callback with an invalid or expired code. Australian teams often develop across Sydney, Perth, and Melbourne, so shared environment variables and documented redirect URIs prevent local configuration differences.
Keep secrets in a secret manager or deployment platform rather than committing them to Git. Before launch, review these operational details:
- Use HTTPS everywhere outside localhost.
- Restrict authorised redirect URIs to known environments.
- Configure session timeout and secure, HTTP-only cookies.
- Monitor failed callbacks and unusual login activity.
- Verify consent-screen branding and production publishing status.
For a stateless REST API, browser-based OAuth2 login is usually the wrong session model. Use the OAuth2 authorisation code flow with a suitable token strategy, or let a dedicated identity platform issue access tokens. For a traditional Spring MVC website, the session-based configuration above is a straightforward and maintainable starting point.