Handling OAuth2 login in Grails with Spring Security
OAuth2 login lets a Grails application delegate authentication to an identity provider such as Google, Microsoft Entra ID, GitHub, or an organisation’s own OpenID Connect server. Instead of storing passwords, the application sends a user to the provider, receives a verified response, and creates a local authenticated session. Spring Security handles much of this exchange, while Grails supplies the application structure, configuration, and domain model.
For teams building software in Australia, this approach can simplify access for staff and customers who already use Microsoft 365, Google Workspace, or a business identity platform. It also supports clearer privacy decisions under the Privacy Act 1988 and the Australian Privacy Principles, because the application can minimise the identity data it stores. The key is to treat OAuth2 as an authentication workflow, not as a simple “social login” button.
How the OAuth2 login flow works
The modern login flow normally uses OAuth 2.0 Authorization Code with OpenID Connect. A visitor selects “Sign in with Google” or another provider, and Grails redirects the browser to the provider’s authorisation endpoint. The provider authenticates the person, asks for consent when necessary, and redirects the browser back to a registered callback URL in the Grails application.
Spring Security exchanges the returned authorisation code for tokens on the server side. The ID token describes the authenticated identity, while the access token is intended for calling the provider’s APIs. These tokens have different purposes, so an application should not treat an access token as proof of identity without validating it through the correct OpenID Connect process.
After successful validation, Spring Security creates an authenticated principal and stores the relevant details in the security context. Your application can then use the principal’s subject identifier, email address, display name, or provider name to find a local user. The provider’s stable sub claim is usually a better account key than an email address, because email addresses can change or be reused.
Groovy’s concise syntax is useful when wiring these pieces together, particularly for developers moving from Java. A short Groovy overview can help clarify closures, maps, and configuration conventions that appear in Grails security examples.
Add the Spring Security pieces to Grails
Start with a Grails application that uses a supported Spring Security Core plugin. The exact dependency version depends on whether the project runs Grails 5, 6, or 7, so check the plugin’s compatibility matrix rather than copying a version from an unrelated tutorial. OAuth2 client support commonly comes from Spring Security’s OAuth2 Client module, either directly or through the Grails security integration being used.
A typical Gradle setup may resemble the following. Package names and versions should be adjusted to match the application’s Grails and Spring Boot release:
dependencies {
implementation "org.grails.plugins:spring-security-core:<compatible-version>"
implementation "org.springframework.boot:spring-boot-starter-oauth2-client"
}
Some Grails plugins expose their own configuration keys or helper classes. Read the documentation for the installed plugin and verify whether it expects application.yml, application.groovy, or a database-backed request map. Mixing configuration styles from different major versions is a common reason for startup errors.
The application also needs a local user model and a way to represent roles. A simple user record might contain a username, provider name, provider subject, email, display name, and enabled flag. Avoid making the email address the only identifier if the application may support multiple providers. The same person can have different identities at Google and Microsoft, and two providers may return the same email for separate accounts.
Before changing security rules, browse a few practical Grails code examples to compare conventions for controllers, services, and configuration. Then keep authentication logic in a service rather than placing account-linking decisions inside a controller action.
Configure the identity provider and callback
Each provider requires an application registration. Create a client ID and client secret, select the required OpenID scopes, and register the exact redirect URI. For a local Grails server, the callback might use http://localhost:8080/login/oauth2/code/google. A production address could be https://portal.example.com/login/oauth2/code/google. Differences in scheme, hostname, port, path, or trailing slash can cause the provider to reject the request.
A Spring Security configuration commonly looks like this in application.yml:
spring:
security:
oauth2:
client:
registration:
google:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
scope:
- openid
- profile
- email
provider:
google:
issuer-uri: https://accounts.google.com
The issuer-uri allows Spring Security to discover the provider’s authorisation, token, and JSON Web Key Set endpoints. Microsoft Entra ID requires a tenant-specific issuer or a suitable multi-tenant configuration. GitHub uses OAuth2 but does not provide the same OpenID Connect identity claims by default, so the application may need a user-information request and a carefully defined account-matching strategy.
Never commit client secrets to Git, including private repositories that are mirrored or copied into build systems. Use environment variables, a secrets manager, or the secret store provided by the hosting platform. In Australia, a team may deploy to AWS Sydney, Azure Australia East, or Google Cloud Sydney; the cloud region does not remove the need to protect credentials or document where personal information is processed.
A minimal Spring Security filter-chain configuration can permit the login endpoints while requiring authentication elsewhere:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) {
http
.authorizeHttpRequests { rules ->
rules
.requestMatchers("/", "/login/**", "/error", "/assets/**").permitAll()
.anyRequest().authenticated()
}
.oauth2Login { oauth ->
oauth.loginPage("/login")
}
return http.build()
}
The exact DSL can vary with the Spring Security version integrated into Grails. If the application already uses the Grails Spring Security Core plugin, use its documented extension points rather than defining competing filters. Two security configurations that both create authentication filters can produce confusing redirects and inaccessible resources.
Map identities and protect application data
A successful provider response does not automatically mean the user should receive application access. The callback should pass the authenticated principal to a service that creates or finds a local account, assigns a default role, records the provider identity, and applies any business rules. For an internal application, you may restrict access to an approved email domain or require that the person already exists in an employee directory.
Use an immutable provider subject as the link to the external account. Store only the claims needed by the application, such as a display name and verified email address. If your product operates in Melbourne, Brisbane, or elsewhere across Australia, explain in the privacy notice whether identity information is stored locally, transferred to an overseas provider, or processed by an overseas cloud service. The Australian Privacy Principles make transparency and responsible handling important parts of the design.
Role checks should remain explicit. A login proves identity; it does not grant administrator privileges. Use method-level or URL-level authorisation for sensitive actions, and make role assignment an auditable operation. A first-time user should normally receive a restricted role until an administrator or an approved provisioning rule grants additional access.
Session handling deserves attention as well. Use HTTPS outside local development, configure secure and HTTP-only cookies, set a suitable session timeout, and invalidate the session on logout. If the application serves users in Perth, Adelaide, and Sydney, users may access it from changing networks and devices, including shared office machines and mobile connections. A visible logout action and sensible re-authentication controls reduce the impact of a lost device.
The following checks help separate authentication problems from authorisation problems:
- Confirm the provider returns an ID token with the expected issuer and audience.
- Verify the local account uses a stable provider subject, not only an email address.
- Check that new users receive the least-privileged default role.
- Test logout, session expiry, and access to restricted URLs.
Test the callback and prepare production deployment
Test the complete browser flow with a real provider account before writing extensive application logic. Confirm that an unauthenticated visitor reaches the provider, returns to the correct callback, receives a local session, and can access an authenticated page. Test a first login, a returning login, a disabled local account, and an account whose provider email has changed.
Use separate OAuth client registrations for development, staging, and production. Localhost callbacks should not be reused in a live registration, and a production callback should not be made broadly permissive. When deploying behind an Nginx proxy, load balancer, or platform router, configure forwarded headers correctly so Grails and Spring Security understand that the original request used HTTPS.
Australian operational details can affect testing. Public holidays may change support coverage, daylight saving differs between states, and a scheduled deployment planned for Sydney time may occur at a different local time in Queensland or Western Australia. Record timestamps in UTC and display them in the user’s intended timezone. This prevents a login audit or account lockout report from becoming ambiguous during an incident.
Privacy and security records should cover the provider, requested scopes, retention period, account-linking rules, and breach response process. If an incident exposes identity data, the Notifiable Data Breaches scheme may apply, depending on the organisation and the seriousness of the breach. Legal advice is appropriate for the specific business, especially where the application handles health, financial, education, or government-related information.
For production readiness, keep these checks close to the deployment process:
- Store client secrets in a managed secret store and rotate them periodically.
- Register exact HTTPS redirect URIs for every live environment.
- Monitor failed callbacks without logging tokens, claims, or personal data unnecessarily.
- Verify proxy headers, cookie security, clock synchronisation, and session expiry.
When diagnosing a failed login, inspect the browser redirect, application logs, provider registration, and server clock in that order. An invalid_redirect_uri error usually points to registration or proxy configuration. An invalid issuer or signature error often indicates a tenant, discovery, or clock problem. A successful login followed by a forbidden response generally means the local account or role mapping is incomplete.
A reliable implementation keeps the provider-specific code narrow and the application’s identity model independent. That makes it easier to add Microsoft after Google, replace a provider, or introduce single sign-on for a business customer without rewriting every secured controller. It also makes automated testing practical: mock the authenticated principal and test local account and role decisions separately from the external network exchange.
Build the first version with one provider, a small set of scopes, and a clear local-user policy. Run it through development and staging, inspect the callback under a real reverse proxy, and document the data flow for your team. Once the login path is stable, add providers and account-linking features deliberately, using least privilege and strong audit records as the foundation.