Cross-Site Request Forgery (CSRF or XSRF)
Context
This attack bases on the fact that cookies are always send when a request happens. A malicious site could embed a request using the current user session to do requests on their behave.
To prevent this all mutation requests (ie POST) need to set a special header (x-csrf-token). On the server side the tokens is compared to its cookie value.
Follow this link read more about it.
How to add it to your project
To enable CSRF protection in you project add the csrfMiddleware to the api. This will on the client side set a x-csrf-token header matching the cookie value.
// file: templates/shop/src/shop/client/api/creators/api.ts
import { csrfMiddleware } from '@archibald/server';
// ...
export const api = createApi({ options: getAPIDefaultOptions() });
if (process.env.APP_CODE === 'client') {
api.register(csrfMiddleware);
}
// ...
Inside the server the csrf plugin needs to be registered and can also be configured. for a full list of options please view the crumb documentation. Keep in mind that changing the base configuration can break the plugin. For example the plugin relies on restful to be set to true.
// file: templates/shop/src/shop/server/module/server.tsx
import { CoreServer, DefaultPlugins, SwaggerPlugin, CSRFPlugin } from '@archibald/server';
export class Server extends CoreServer {
// ...
protected async initServer() {
await this.createServer({
app: {
csrf: {
// configure options to overwrite ie:
logUnauthorized: false,
},
}
})
}
public async initPlugins() {
// ...
await this.registerPlugins([...DefaultPlugins, SwaggerPlugin, CSRFPlugin]);
}
}