CSRF Protection
Cross-Site Request Forgery (CSRF) Protection
Accella has built-in CSRF protection. When sending POST or other non-GET requests, you must include the appropriate token in the request, or an InvalidAuthenticityToken error will occur. If you use the framework features to create forms, the CSRF token is automatically generated and included in the request.
Creating Forms Without Framework Features
If you are creating a form manually, use the CsrfTokenField
component to include the token as shown below.
---import CsrfTokenField from "accel-web/form/CsrfTokenField.astro";---
<form method="POST"> <CsrfTokenField /> <!-- ... --></form>
Using CSRF Tokens in Ajax Requests
Use the CsrfMetaTags
component in your layout file to generate meta tags. Set the token from these meta tags in the X-CSRF-Token
request header.
---import { CsrfMetaTags } from "accel-web";---
<!-- ... --> <head> <CsrfMetaTags /> <!-- Meta tags like the following will be generated: <meta name="csrf-param" content="authenticity_token"> <meta name="csrf-token" content="xxxx"> --> </head><!-- ... -->
Helper Functions for AuthenticityToken
defineAuthenticityToken
and validateAuthenticityToken
are used to prepare and validate tokens for requests.
These are used within the Astro middleware provided by Accella.
import { RequestParameters } from "accel-web";import { defineAuthenticityToken, validateAuthenticityToken } from "accel-web/csrf";import { APIContext } from "astro";import { getSession } from "./session";
export const onRequest = async (context: APIContext, next: any) => { const { cookies, request, params, locals } = context; locals.session = getSession(cookies); locals.params = await RequestParameters.from(request, params);
defineAuthenticityToken(locals, locals.session); validateAuthenticityToken(locals.params, locals.session, request);
return await next();};
When defineAuthenticityToken
is executed, the token can be accessed via Astro.locals.authenticityToken
. This token is automatically embedded when generating forms using formFor
.
validateAuthenticityToken
validates the authenticity token for POST, PUT, PATCH, and DELETE requests. If the tokens do not match, an InvalidAuthenticityToken
exception is thrown.