BlueGate CSRF
Add CSRF protection to forms and links. This module requires writing routes using ES6 classes with the BlueGate class module and requires sessions using BlueGate session.
This module can protect forms and links against CSRF-attacks. See the OWASP site for more information about CSRF.
Installation
Install using npm install bluegate-csrf bluegate-class bluegate-session
Quick example
Load the module in the main application file.
var BlueGate = ;var app = ;app; app;app;app;
Add a hidden element named csrfToken
with the token retrieved from the function paramaters.
/** * @Route("GET /form") */moduleexports = { return '<html>' + '<form action="/form">' + '<input type="hidden" name="csrfToken" value="' + csrfToken + '" />' + '<input type="submit" />' + '</form>' + '</html>'; }
And add the Csrf-annotation in the POST route:
/** * @Route("POST /form") * @Post("name", type="string") * @Csrf(true) */ { return name ; }
The form is now protected against CSRF-attacks when the user has a session.
An error is thrown in the prevalidation
hook when the token is missing or invalid.
Protection of links
You should consider CSRF protection for links that can perform harmful actions.
/** * @Route("GET /link") */ { return `<a href="/link/action/">do something</a>`; }
The route for the linked page needs to have the Csrf-annotation and must map the path part with the name "csrfToken".
/** * @Route("GET /link/action/<csrfToken:string>") * @Csrf(true) */ { return {}; }
Security considerations
The protection is only active for users with a session (i.e. authenticated users). Visitors without a session are not protected for performance reasons, because that will conflict with any form of page caching. It is however highly unlikely that anonymous requests involve state changing actions and thus require CSRF protection.
The CSRF-token is based on the session id, but does not include the whole session id to avoid leaking it.
Using GET requests for state changing requests is discouraged when using sensitive data, even when adding CSRF protection. This is because disclosure of tokens is more likely for GET requests.