1 | initial version |
Enable CSRF protection in the backend: This involves adding an XSRF-Token to the cookie/session on every request.
Obtain the XSRF-Token: You can obtain the XSRF token by intercepting an initial request to the server that is protected by CSRF. Most modern web frameworks have a helper function that adds the XSRF token to the response.
Add the XSRF-Token header to RTK Query: The XSRF-Token must be sent to the server with every request as a request header. You can add the header using fetchBaseQuery
config object by providing a function that will retrieve the XSRF-Token from the storage.
Verify the XSRF-Token in the backend: When the server receives the request with the XSRF-Token, it should compare this value with the value stored in the cookie/session.
Return a 401 Unauthorized status code: If the XSRF-Token is invalid, the server should return a 401 status code to the client.
To obtain the XSRF-Token, you can use the following code:
const getCsrfToken = async () => {
const response = await fetch('/api/get-csrf-token');
const { csrfToken } = await response.json();
return csrfToken;
};
const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: 'https://api.example.com',
prepareHeaders: (headers, { getState }) => {
const csrfToken = getState().auth.csrfToken;
if (csrfToken) {
headers.set('X-XSRF-Token', csrfToken);
}
return headers;
},
}),
endpoints: (builder) => ({
// ...
}),
});
const store = configureStore({
reducer: api.reducerPath,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
});
store.dispatch((dispatch) => {
dispatch(api.util.setMatchedEndpoints());
dispatch(getCsrfToken()).then((csrfToken) =>
dispatch({ type: 'auth/csrfTokenReceived', payload: csrfToken })
);
});