Enhance Frontend with CSRF
Send custom CSRF request headers to C# endpoints.
You'll need to configure your AJAX client to take the token out of the CSRF cookie in the browser and set it into a custom CSRF header with outgoing API calls to C#.
Axios
Configure Axios to include the CSRF token in the request headers.
// api-client.ts
import axios from 'axios';
const apiClient = axios.create({
baseURL: `<csharp-server-domain>/api`,
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
// withCredentials: true, // if dealing with CORS
});
export { apiClient };
To handle any 403 Forbidden
HTTP errors returned by the CSRF middleware, you can add/enhance an Axios interceptor to handle that appropriately. For example:
// api-client.ts
import axios from 'axios';
import { isUnauthorized, redirectToLogin } from '@/utils/helpers';
const apiClient = axios.create({
baseURL: `<csharp-server-domain>/api`,
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
// withCredentials: true, // if dealing with CORS
});
// Any HTTP 401 OR 403 response should redirect the user to the Login page.
const unauthorizedAccessInterceptor = (error: unknown) => {
if (isUnauthorized(error) || error.response?.status === 403) {
redirectToLogin();
}
return Promise.reject(error);
};
apiClient.interceptors.response.use(undefined, unauthorizedAccessInterceptor);
export { apiClient };
Alternatively, you can handle forbidden errors with more precision by adding custom error handling in your API request's catch block.
// example-component.ts
import axios from 'axios';
// You could implement another helper function for checking 403 responses.
import { isUnauthorized, isForbidden, redirectToLogin } from '@/utils/helpers';
export function ExampleComponent() {
const handleApiCall = async () => {
try {
const response = await axios.get(`<your-csharp-server-domain>/test`);
alert('Success!');
} catch (error: unknown) {
if (isUnauthorized(error) || isForbidden(error)) {
redirectToLogin();
} else {
console.error('Unexpected error:', error);
alert('Something went wrong!');
}
}
};
return (
<button onClick={handleApiCall}>
Make API Call
</button>
);
}
Fetch
Unfortunately, Fetch doesn't have automatic handling for CSRF. You'll have to implement that logic from scratch.
// You'd need to implement this theoretical getCookie() function.
const csrfToken = getCookie('XSRF-TOKEN');
fetch('/api/endpoint', {
credentials: 'include',
headers: {
'X-XSRF-TOKEN': csrfToken
}
});
Updated 8 days ago
Now we can test your CSRF middleware set up to make sure it's working.