Provides a modified fetch
that is automatically secure against CSRF attacks for non-idempotent HTTP methods.
This enhancer handles csrf protection by adding a server side middleware that checks for a valid csrf token on requests for non-idempotent HTTP methods (e.g. POST).
yarn add fusion-plugin-csrf-protection
import {createPlugin} from 'fusion-core';
import {FetchToken} from 'fusion-tokens';
const pluginUsingFetch = createPlugin({
deps: {
fetch: FetchToken,
},
provides: ({fetch}) => {
return {
getUser: () => {
return fetch('/get-user');
}
}
},
});
// src/main.js
import React from 'react';
import {FetchToken} from 'fusion-tokens';
import App from 'fusion-react';
import CsrfProtectionEnhancer, {
CsrfIgnoreRoutesToken,
} from 'fusion-plugin-csrf-protection';
import fetch from unfetch;
export default () => {
const app = new App(<div></div>);
app.register(FetchToken, fetch);
app.enhance(FetchToken, CsrfProtectionEnhancer);
// optional
__NODE__ && app.register(CsrfIgnoreRoutesToken, []);
}
import CsrfProtection from 'fusion-plugin-csrf-protection';
The csrf protection plugin. Typically, it should be registered to the FetchToken
. Provides the fetch api and
a server side middleware for validating csrf requests.
import {FetchToken} from 'fusion-tokens';
The canonical token for an implementation of fetch
. This plugin is generally registered on that token.
For more, see the fusion-tokens repo.
import {CsrfIgnoreRoutesToken} from 'fusion-plugin-csrf-protection';
A list of routes to ignore csrf protection on. This is rarely needed and should be used with caution.
Types
type CsrfIgnoreRoutes = Array<string>;
Default value
Empty array []
const response: Response = fetch('/test', {
method: 'POST',
})
fetch: (url: string, options: Object) => Promise
- Client-only. A decorated fetch
function that automatically does pre-flight requests for CSRF tokens if required.
See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API for more on the fetch api.