SAML authentication in a Grails application
SAML authentication lets a Grails application delegate sign-in to a trusted identity provider. Instead of validating a password locally, the service provider sends the browser to the provider, receives a signed assertion, and creates a normal local web session. This gives staff and enterprise customers single sign-on while keeping Groovy controllers focused on authorised business data.
The important distinction is between authentication and authorisation. SAML can prove who the user is and carry group attributes, but the Grails application must still decide which roles may access each action. A secure implementation therefore covers metadata, certificates, assertion validation, user sessions, role mapping, logout and failure handling rather than only adding a login button.
Many Australian organisations in Sydney, Melbourne and elsewhere use Microsoft 365 with Entra ID, or retain Active Directory Federation Services on premises. SAML is common when a customer or internal platform will not implement OpenID Connect. Australian deployments should also account for the Privacy Act 1988 and the Australian Privacy Principles where applicable, especially when identity attributes or logs leave the organisation.
Before writing filters, review the site’s core security guidance and document the trust boundary. Decide which identity providers, tenants, groups and sign-on methods are allowed. That short design record prevents an overly broad SAML endpoint from becoming a way to bypass local authorisation.
Preparing the identity provider and service provider
Begin with the identity provider administrator. Obtain its federation metadata, which normally contains the single sign-on URL, signing certificates and supported bindings. Register the Grails application as a service provider with a stable entity ID, an HTTPS assertion consumer service URL, the required name identifier format and any optional single logout endpoints. Separate registrations for development, staging and production prevent test assertions from being accepted in production.
The application also needs its own key pair. The public X.509 certificate can be published in service provider metadata, while the private key signs authentication requests and decrypts encrypted assertions. Keep this key in a secret manager or protected deployment environment rather than committing it to source control. Use modern algorithms supported by the provider, and agree on a certificate rotation process before the first release.
Configuration should distinguish public identity data from sensitive credentials. Entity IDs, metadata locations and the public certificate are not secrets, but private keys and their passphrases are. In a clustered Grails deployment, every instance must receive the same configuration and be able to reach the identity provider. Environment-specific endpoints are useful for testing, yet the production service provider registration must exactly match the URLs visible to users.
Configuring SAML in the Grails application
Spring Security’s SAML2 service-provider support is a practical foundation because it handles the protocol machinery instead of leaving the application to parse XML assertions. Add a version that matches the Spring Security libraries supplied by the Grails security plugin:
implementation "org.springframework.security:spring-security-saml2-service-provider"
Check the plugin’s supported Spring Security version before upgrading dependencies. The exact configuration DSL has changed between generations, but the underlying requirements remain stable: a relying-party registration, a published metadata document, signing or decryption credentials, and a protected SAML login route.
A custom configuration object can keep provider-specific values outside the controllers:
saml:
corporate:
registrationId: corporate
entityId: https://orders.example.au/saml/metadata
acsUrl: https://orders.example.au/saml/acs
idpMetadataUri: https://idp.example.au/federation/metadata
idpSigningCertificate: ${SAML_IDP_SIGNING_CERTIFICATE}
spPrivateKey: ${SAML_SP_PRIVATE_KEY}
spPrivateKeyPassword: ${SAML_SP_PRIVATE_KEY_PASSWORD}
Map those values into the library’s registration API. This example is illustrative and may need minor method-name adjustments for the selected plugin version:
RelyingPartyRegistration corporate = RelyingPartyRegistrations
.fromMetadataLocation(settings.idpMetadataUri)
.registrationId(settings.registrationId)
.entityId(settings.entityId)
.assertionConsumerServiceLocation(settings.acsUrl)
.signingX509Credentials(signingCredential)
.decryptionX509Credentials(decryptionCredential)
.build()
Expose the service provider metadata at a stable, publicly reachable endpoint and allow unauthenticated access only to that endpoint and the assertion consumer service. Other routes should remain under the normal Spring Security rules. Avoid building a separate Grails interceptor that recognises SAML parameters independently, because it can accidentally bypass the framework’s session and authorisation controls.
Processing sign-in and assigning local roles
A typical browser exchange starts when an unauthenticated user requests a protected Grails controller. The application redirects the browser to the identity provider with an authentication request. After authentication, the provider posts a SAML response to the assertion consumer service. The library must then verify the response signature, issuer, audience, destination, timestamps, replay status and subject confirmation before the application trusts the asserted identity.
The identity provider can send group or role attributes, but those values should not become local authorities without an explicit mapping policy. A useful pattern is to read the groups attribute, compare it with an allowlist maintained by the application and translate approved groups into fixed authorities:
def rawGroups = principal.attributes['groups'] ?: []
def groups = rawGroups instanceof Collection ?
rawGroups.collect { it.toString() } : [rawGroups.toString()]
def authorities = groups
.findAll { allowedGroups.contains(it) }
.collect { "ROLE_${it.replaceAll('[^A-Za-z0-9_]', '_').toUpperCase()}" }
A more precise implementation belongs in a Spring Security GrantedAuthoritiesMapper or authentication success handler. It should also create or update the local user record, reject disabled accounts and handle a missing or unexpected group. Role names, department claims and email addresses should never be accepted as unrestricted application commands.
Once the assertion passes validation, the library establishes the SecurityContext, and Grails should save that context using the configured session or security-context repository. Subsequent requests use the local session rather than contacting the provider on every request. Apply sensible idle and absolute timeouts, rotate the session identifier after login and protect state-changing forms against cross-site request forgery.
Single logout requires careful wording because identity providers implement it differently. Always provide a local logout action that clears the Grails session. If federation logout is required, confirm that the provider supports the chosen logout binding, validate its signed request and maintain a short-lived correlation record. Never treat an unsigned logout request as sufficient evidence that a user has ended the provider session.
Testing and operating the federation
Test both service-provider-initiated and identity-provider-initiated sign-on if the business requires both. Include successful authentication, a missing group, an expired assertion, a wrong audience, an invalid signature, a replayed response and a user disabled at the provider. Automated tests should prove that invalid assertions never create a session, while a browser test should confirm that the post-login redirect reaches the originally requested Grails controller.
Time synchronisation deserves particular attention in Australia. SAML timestamps are expressed in UTC, but servers, identity providers and test devices operate across Australian Eastern Standard Time, Australian Eastern Daylight Time and other state zones. Daylight-saving changes must not create failures, and a clock-skew tolerance should be narrowly configured rather than made unnecessarily large. The Australian Signals Directorate’s Essential Eight is a useful local reference when defining authentication controls; SAML provides federation, while multifactor authentication remains an identity-provider responsibility.
Deployment behind a load balancer or reverse proxy also requires accurate URL generation. Preserve the public scheme and host, and trust forwarded headers only from known proxies. Store private keys in a managed secret service, maintain an overlap period during certificate rotation and publish the updated metadata before replacing the old signing certificate. Centralised logs should record successful logins, rejected assertions and role changes without recording complete assertions or unnecessary personal information.
Separate public properties deserve their own trust boundaries. A Grails microsite promoting wagering-free casino games, for example, should not copy a staff single sign-on registration into production. It should use a separate provider tenant, client registration and redirect allowlist. If the wider Australian platform offers actual wagering, identity federation must sit alongside applicable Interactive Gambling Act requirements, state licensing, age verification, anti-money-laundering controls and responsible-gambling safeguards; SAML does not deliver those controls itself.
A rollout checklist and launch actions
A controlled launch depends on clear ownership, tested configuration and an agreement about what happens when the provider or certificate expires.
- Register a unique service provider entity ID for each environment and verify every assertion consumer URL through the public internet.
- Pin trusted identity-provider certificates, document rotation dates and maintain an overlap period that avoids an authentication outage.
- Require signed assertions and validate audience, issuer, destination, timestamps, replay protection and subject confirmation in the SAML library.
- Map only explicitly approved identity-provider groups to a small set of local roles, with unknown claims denied by default.
- Keep private keys outside source control, restrict access to deployment identities and test restoration from the production secret store.
- Exercise expired assertions, disabled users, proxy routing, clustered sessions and single logout before inviting customers to use the service.
Start with a test tenant and one approved corporate identity provider. Publish valid metadata, complete a successful assertion exchange, assign a test user to the intended Grails role and run the failure scenarios before scheduling a production cut-over. Involve security, operations and support teams early so certificate rotation, incident response and customer assistance have clear procedures from the first login. Begin with a test tenant, publish valid metadata, complete one successful assertion exchange, and only then schedule the production cut-over.