Skip to content

Commit 89d5b7e

Browse files
committed
Support CSRF protection in GraphiQL with cookie-to-header strategy
Prior to this commit, secured applications with CSRF protection could not easily use the GraphiQL integration shipped with Spring for GraphQL, as the JavaScript code would not work with any CSRF protection strategy for single page apps. This commit checks whether the main HTTP response contains a `XSRF-TOKEN` Cookie value, and uses it as a `X-XSRF-TOKEN` request header for the next AJAX request to the `/graphql` endpoint. Note that a specific configuration must be set in Spring Security to achieve that: * the CSRF token must be sent as a response Cookie for the initial authenticated request * if the application is protected against BREACH, all new token values must be sent as response cookies as well and a request handler must be configured Closes gh-758
1 parent bb819f9 commit 89d5b7e

File tree

1 file changed

+4
-6
lines changed
  • spring-graphql/src/main/resources/graphiql

1 file changed

+4
-6
lines changed

spring-graphql/src/main/resources/graphiql/index.html

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,17 @@
3030
const wsPath = params.get("wsPath") || "/graphql";
3131
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
3232
const subscriptionUrl = `${wsProtocol}//${location.host}${wsPath}`;
33-
34-
const gqlFetcher = GraphiQL.createFetcher({
35-
url,
36-
subscriptionUrl,
37-
});
38-
33+
const gqlFetcher = GraphiQL.createFetcher({'url': url, 'subscriptionUrl': subscriptionUrl});
3934
const explorerPlugin = GraphiQLPluginExplorer.explorerPlugin();
35+
const xsrfToken = document.cookie.match(new RegExp('(?:^| )XSRF-TOKEN=([^;]+)'));
36+
const headers = xsrfToken ? `{ "X-XSRF-TOKEN" : "${ xsrfToken[1] }" }` : `{}`;
4037
ReactDOM.render(
4138
React.createElement(GraphiQL, {
4239
fetcher: gqlFetcher,
4340
defaultVariableEditorOpen: true,
4441
headerEditorEnabled: true,
4542
shouldPersistHeaders: true,
43+
headers: headers,
4644
plugins: [explorerPlugin]
4745
}),
4846
document.getElementById('graphiql'),

0 commit comments

Comments
 (0)