Locking Down a Grails App with CORS Configuration
Cross-origin resource sharing (CORS) is the browser protocol that decides whether JavaScript on one site may read a response from another site. A Grails front end at https://portal.example.com.au and an API at https://api.example.com.au are different origins, so the API must explicitly approve the browser request before the page can inspect the result. Without that approval, the browser blocks the response, even when the Grails controller returns valid JSON.
Locking down a Grails app with CORS configuration means treating browser access as a narrow, reviewed capability rather than blanket permission. The practical goal is to permit known clients, reject unknown ones, handle preflight requests and keep credential handling separate from origin control. The examples below use Grails’ Spring-based web stack and can be adapted to the configuration style used by your project version.
How browsers define an origin
An origin combines a scheme, host and port. https://app.example.com.au is therefore different from http://app.example.com.au, https://api.example.com.au and https://app.example.com.au:8443. Subdomains are separate origins too, so approving https://app.example.com.au does not approve https://admin.example.com.au. Paths and query strings are not part of an origin, which means an allowlist entry should contain no trailing slash, filename or route.
Only browsers enforce CORS. Server-to-server calls, mobile applications and command-line clients can send requests without receiving CORS restrictions. CORS controls whether browser JavaScript can read a response; it does not stop the request from reaching the Grails server or prevent a request with side effects. Authentication, authorisation and input validation must still happen inside every API operation.
Some browser requests have no Origin header, while sandboxed frames and certain privacy redirections can produce Origin: null. These cases require deliberate treatment rather than a broad allowance. A missing origin is not proof that a request is trusted, and null should not be accepted merely because it appears in local development.
Building a deliberate origin allowlist
Start by inventorying every browser client that calls the API. A customer portal, partner website and administrator dashboard may each use a different hostname, even when they belong to the same organisation. Record the exact production origins, separate development origins and assign an owner to each entry. Localhost should appear only in development configurations, using its real port such as http://localhost:3000.
An allowlist is safer than reflecting whatever origin arrives in the request. Reflection works only when the received value has already been checked against an approved set. Spring supports wildcard origin patterns, including patterns for approved subdomains, but explicit origins are easier to audit and prevent a compromised or forgotten subdomain from inheriting access.
A legitimate sports-market integration might involve the 188esport platform; that relationship should still produce one verified canonical origin rather than a broad rule. Confirm the scheme, hostname and any non-default port before adding it to configuration. Keep separate lists for production, staging and local development, and remove entries when a client is retired or its domain changes.
Applying CORS in a Grails application
Spring’s CorsFilter provides a practical implementation for Grails applications. Place this class in a configuration package scanned by the project, adapting the path to the Grails version:
package au.com.example.security
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
@Configuration
class BrowserCorsConfiguration {
@Bean
CorsFilter corsFilter() {
def configuration = new CorsConfiguration()
configuration.addAllowedOrigin('https://app.example.com.au')
configuration.setAllowedMethods(['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
configuration.setAllowedHeaders([
'Authorization',
'Content-Type',
'X-Correlation-Id'
])
configuration.setAllowCredentials(true)
configuration.setMaxAge(3600L)
def source = new UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration('/api/**', configuration)
new CorsFilter(source)
}
}
The path pattern limits the policy to API routes. Another registration can cover a different path, but applying CORS to every static asset or controller is rarely necessary. Replace the literal origin and header list with environment-specific configuration, and give each environment its own deployment values rather than switching behaviour through a hidden runtime condition.
The filter must run early enough to answer preflight requests before authentication or CSRF rules reject them. Verify that the project’s security chain actually uses the CORS configuration. Some Spring Security setups require a CorsConfigurationSource bean, while others register a CorsFilter directly. A GET normally reaches the controller without a preflight, whereas a JSON POST or a request containing Authorization usually triggers an OPTIONS check first.
Do not disable authentication because an origin is approved. CORS approval and user permission answer different questions. Every controller should still verify the session or token, apply authorisation rules and validate submitted data. The CORS layer should only decide which browser origins may read the response.
Protecting credentialed cross-origin requests
Credentialed requests include browser cookies or other user credentials. The client opts in with credentials: 'include', and the server acknowledges this with Access-Control-Allow-Credentials: true:
const response = await fetch('https://api.example.com.au/api/profile', {
credentials: 'include',
headers: {
'Accept': 'application/json'
}
})
A wildcard origin cannot be used with credentialed requests. The response must contain one exact approved origin, and the configured list must reject near matches such as an unapproved subdomain. If the API does not use browser cookies, leave credential support disabled where the client architecture permits it, then confirm that bearer-token and preflight behaviour still works.
Cookie security requires independent controls. Use Secure, HttpOnly and an appropriate SameSite policy, while recognising that third-party-cookie restrictions can block cookies even when CORS succeeds. CORS also does not replace CSRF protection: retain synchroniser tokens or another suitable defence, and use origin or referer checks as additional context rather than the only safeguard.
Testing CORS behaviour across workflows
Browser developer tools provide the clearest view of CORS. Open the Network panel, select the API call and inspect both the preflight OPTIONS request and the actual response. Check that the response names the requesting origin, lists the required methods and headers, and includes Vary: Origin when caches may handle multiple origins.
A preflight can also be reproduced from the command line:
curl -i -X OPTIONS "https://api.example.com.au/api/orders" \
-H "Origin: https://app.example.com.au" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: authorization,content-type"
A successful response should include Access-Control-Allow-Origin: https://app.example.com.au, Access-Control-Allow-Methods: POST, the permitted request headers and a suitable preflight cache duration. Then send the actual request and confirm that the same origin policy remains in force. A response to an unapproved origin should omit the allow-origin header, although the request may still have reached the server.
Turn these checks into automated regression tests. Cover an approved origin, a near miss such as a sibling subdomain, an untrusted origin and, where relevant, null. Include tests for credentialed and non-credentialed requests. Preflight responses may be cached for an hour, so restart the application or use a cache-busting request during manual testing when changing configuration.
Deploying the policy for Australian services
Australian hosting choices affect latency and operational resilience. AWS provides the ap-southeast-2 Region in Sydney and ap-southeast-1 in Melbourne, allowing Grails deployments to remain close to users in major eastern cities. A hostname can still use a cross-origin API, but the API and static assets should be deployed consistently across the selected Australian regions, with failover and health checks tested separately from the CORS policy.
Browser access also forms part of a broader privacy and security posture. Where the Privacy Act 1988 and the Australian Privacy Principles apply, CORS headers do not make an organisation compliant by themselves. They control browser response sharing, not the collection, purpose, storage or disclosure of personal information. The OAIC’s Notifiable Data Breaches scheme may also create notification obligations following a serious compromise, making least-privilege API access and detailed audit trails important.
The Australian market includes major banks and a prominent sports betting sector. Many consumers move between online banking, betting accounts and mobile apps during daily transactions, so several legitimate browser origins may exist without belonging to the same company. Each relationship needs a documented owner and exact origin. Mobile applications usually fall outside browser CORS controls, so their authorisation model should be reviewed separately rather than folded into the website allowlist.
Follow the Australian Signals Directorate’s Essential Eight where appropriate, particularly secure configuration, privileged access management and application security. Log rejected origins and unusual preflight patterns without recording cookies, authorisation tokens or other secrets. Alerts should distinguish normal partner traffic from repeated probing, while access to the origin inventory remains limited to people responsible for security and release management.
Reviewing, monitoring, and maintaining access
Review the origin allowlist on a fixed schedule and whenever a client changes its domain, hosting model or ownership. Expired projects and inactive partner integrations should be removed rather than retained as possible future options. Keep methods and headers limited to actual client requirements, and avoid enabling credential support for APIs that do not need it.
Monitor changes to CORS-related deployment configuration and unexpected increases in preflight requests. A cached browser policy can conceal a server-side change for some time, so include the response headers in release checks and deployment diagnostics. If several origins are configured, verify that each response echoes only the matching origin and that Vary: Origin prevents a shared cache from serving one client’s approval to another.
Before promoting a Grails release, send the approved-origin list and representative preflight responses through contact Grails Example, then turn the review into a documented release check for the development, staging and production environments.