Protecting a Grails REST API Against CSRF Attacks
A Grails REST API can be vulnerable to cross-site request forgery (CSRF) when it authenticates users with cookies. In this situation, a browser automatically attaches the session cookie to requests, including requests initiated by a malicious website. An attacker may therefore cause a logged-in user’s browser to submit an unwanted form, change an account setting, or create a transaction.
CSRF protection needs to match the authentication method and the way the API is consumed. A browser application using a Grails session should send a server-generated token with every state-changing request. An API protected by an Authorization: Bearer token kept outside browser cookies has a different risk profile, although it still needs sound origin, authentication, and access-control rules.
Identify The Authentication Risk
Start by checking how the Grails application stores and sends credentials. Session cookies, remember-me cookies, and authentication cookies are automatically included by browsers on matching requests. If an endpoint accepts POST, PUT, PATCH, or DELETE while relying on one of those cookies, it should generally enforce CSRF validation.
A malicious page does not need to read the API response to carry out an attack. It may submit a hidden HTML form to an endpoint such as /orders, or send a cross-origin request through browser JavaScript. Same-origin policy usually prevents the attacker from reading the response, but it does not necessarily prevent the request from being delivered.
Bearer tokens stored in memory and added explicitly to an Authorization header are less exposed to classic cookie-based CSRF. A hostile site cannot normally add a victim’s bearer token to its own request. However, placing that token in a cookie brings the CSRF concern back, and storing tokens in browser storage introduces separate cross-site scripting and token-theft risks.
Select A Token Strategy
The most common approach for a browser-facing Grails service is a synchroniser token or a cookie-to-header token. The server creates a value that an untrusted external site cannot obtain, while the legitimate front end reads or receives it and returns it in a custom header such as X-XSRF-TOKEN.
Spring Security provides the infrastructure required for this pattern. Depending on the Grails and Spring Security versions in use, the configuration may be supplied by the Grails security plugin, a Spring bean, or a custom filter chain. Use the integration supported by the version of Grails in the application rather than copying settings from a different major release.
For a session-based application, an HTTP-session token repository is a straightforward choice. A cookie token repository can suit a separate JavaScript client because the application can expose the token in a non-HttpOnly cookie while keeping the authentication cookie HttpOnly. The token is not a replacement for authentication; it is proof that the request came through the expected application flow.
An API that serves only non-browser clients may deliberately disable CSRF for a stateless bearer-token chain. That decision should be explicit and documented. Do not disable protection globally merely because one endpoint is consumed by a mobile app or command-line client.
Configure The Grails Security Chain
In a modern Grails application that uses Spring Security, the essential configuration enables CSRF in the filter chain and selects a token repository. A Java-style Spring configuration resembles the following example, although the exact bean registration differs between Grails releases:
@Bean
SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf
.csrfTokenRepository(
CookieCsrfTokenRepository.withHttpOnlyFalse()
)
)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/health", "/csrf-token").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
In a Groovy-based Grails project, the same concepts can be expressed through a Spring configuration class, a resources.groovy bean definition, or the settings supplied by the Grails Spring Security plugin. Confirm that the resulting filter is active by inspecting application startup logs and testing a protected write request. A setting that exists in a configuration file but is not connected to the active filter chain provides no protection.
Keep safe and unsafe HTTP methods separate. GET, HEAD, and OPTIONS should not change server state, while POST, PUT, PATCH, and DELETE should require a valid token when they use cookie authentication. A controller action that updates a record through GET creates a design flaw that CSRF configuration cannot fully repair.
The token endpoint, if one is needed, should return the current token without exposing private business data. Some Spring Security configurations set the token cookie as part of an ordinary response, removing the need for a separate endpoint. Whichever model is selected, ensure the front end can obtain the token before making its first state-changing request.
Send And Validate The Token
A browser client should include the token in a header for every modifying request. For example, a JavaScript client may read the XSRF-TOKEN cookie and use it in X-XSRF-TOKEN:
const token = readCookie("XSRF-TOKEN");
await fetch("/api/profile", {
method: "PATCH",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"X-XSRF-TOKEN": token
},
body: JSON.stringify({ displayName: "Alex" })
});
The exact cookie and header names must match the Spring Security repository. Angular uses a similar convention by default, while a Vue, React, or plain JavaScript client may need a small request wrapper. credentials: "same-origin" is important when the application depends on a session cookie; for a trusted cross-origin front end, use the carefully configured include mode with matching CORS rules.
Never accept a token supplied in a request body simply because it is convenient. A custom header creates a useful browser boundary because a hostile site generally cannot set it through a simple HTML form. Validate the token before the controller performs any state change, and return an appropriate 403 Forbidden response when it is absent or invalid.
The server should compare the submitted value with the value associated with the user’s session or the configured token repository. Do not log complete CSRF tokens, cookies, or session identifiers. In Australian organisations covered by privacy obligations, security logs should be treated as sensitive operational data and retained only for a justified period.
Handle CORS And Cookies Carefully
CSRF tokens do not make an unsafe CORS policy safe. If a Grails API accepts requests from every origin while also allowing credentials, an attacker may be able to interact with the API in ways that defeat the intended browser boundary. Set an explicit allowlist of trusted origins, such as the production web application and approved development hosts.
For a team based in Melbourne with a front end hosted separately from an API in Sydney, the two origins may differ even though both systems belong to the same organisation. Configure the exact schemes, hostnames, and ports used by those deployments. Avoid broad wildcard values such as * when credentials are enabled.
Cookie attributes also matter. Use Secure in production so cookies travel only over HTTPS, select an appropriate SameSite policy, and keep authentication cookies HttpOnly unless a particular client-side requirement prevents it. SameSite=Lax can reduce cross-site request delivery, but it is a defence in depth measure rather than a substitute for server-side token validation.
Review reverse proxies and load balancers as well. A TLS-terminating proxy must forward the correct scheme so Grails and Spring Security know the original request was secure. If several application instances serve a session-based API, configure shared session storage or reliable session affinity; otherwise, a token generated on one instance may not validate on another.
Test The Failure Paths
A useful test suite verifies both rejection and acceptance. Send a POST request with a valid session cookie but no CSRF header, and expect 403. Repeat with an incorrect token and expect the same result. Then send the correct token and verify that the request reaches the controller and changes the intended resource.
Include tests for every state-changing route, including less obvious actions such as password changes, file uploads, invitation acceptance, saved searches, and administrative operations. Test JSON requests as well as form submissions. A route can accidentally bypass protection if it is registered in a separate filter chain or exposed through a plugin with different security rules.
Browser automation should cover token renewal and expired sessions. A user can leave a page open overnight, sign in again in another tab, or receive a rotated session identifier. The client should handle a failed token request without retrying a dangerous operation repeatedly. Return a clear error shape so the front end can obtain a fresh token and let the user retry safely.
Use curl or an API client for controlled checks, but remember that these tools do not reproduce browser cookie behaviour automatically. A security review should also attempt a cross-origin form submission from an unrelated test domain. That test demonstrates whether the server depends on the token rather than merely relying on the browser’s same-origin policy.
Keep Stateless And Stateful APIs Distinct
Many Grails systems expose both a browser session API and a machine-to-machine API. Give them separate security chains or clearly separated route policies. The browser chain can require a CSRF token, while a properly stateless bearer-token chain can disable CSRF only for its own endpoints.
Do not mix authentication styles casually. If a bearer token is issued into a cookie for convenience, the endpoint is effectively cookie-authenticated and should receive CSRF protection. If a refresh token is stored in a cookie, carefully protect the refresh operation as well, since an attacker may target token renewal rather than the business endpoint.
Document the choice in the project’s security notes. This is especially useful when an Australian business has developers in Brisbane, Perth, and remote regional locations working across different clients and environments. A clear matrix showing route, authentication method, cookie use, CSRF requirement, and permitted origins prevents a later change from silently weakening the design.
Pair CSRF checks with authorisation, input validation, rate limiting, audit events, and secure session management. CSRF answers the question “did this browser request come through the trusted application flow?” It does not decide whether the authenticated user may edit a particular invoice or whether the JSON payload is safe.
Deploy And Monitor The Protection
Before deployment, verify that production and staging use HTTPS, secure cookie settings, correct proxy headers, and the intended trusted-origin list. Test the deployed hostname rather than relying only on localhost; cookie domain, SameSite, and CORS behaviour can change between environments.
A practical deployment workflow should include a security smoke test after each release. Teams maintaining services for customers in Sydney or Adelaide may use a hosted environment, a managed platform, or a private cloud, but the same checks apply. The deployment pipeline should fail when a protected write unexpectedly returns success without a token.
If the application is being moved between hosting platforms, review environment variables and proxy configuration instead of assuming the old defaults still apply. The AppFog deployment guide is useful background for understanding the packaging and deployment concerns around a Grails application, while CSRF settings still need to be checked in the target runtime.
Monitor rejected CSRF requests without recording secrets. A sudden rise may indicate a broken front end, an expired session-handling change, or an attack. Record route, timestamp, deployment version, and a privacy-safe user or request identifier. Alert on meaningful patterns, and make sure support staff can distinguish a genuine security rejection from an ordinary stale-page error.
Add CSRF protection to the Grails API as part of the application’s normal security lifecycle: identify cookie-authenticated writes, enable the supported Spring Security mechanism, send the token from trusted clients, and test rejected requests before release. Apply the same discipline to every new endpoint and integration, then review the configuration whenever authentication or hosting changes.