CSRF Protection
You are reading the documentation for version 2 of FoalTS. Instructions for upgrading to this version are available here. The old documentation can be found here.
--
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user’s web browser to perform an unwanted action on a trusted site when the user is authenticated.
Source: OWASP
#
Defense PrincipleFoalTS combines two defenses to protect your application against a CSRF attack. It uses the SameSite
cookie directive and a token-based technique to have in-depth protection.
When enabled, authentication cookies have their SameSite
attribute set to lax
in order to prevent third-party websites from sending authenticated requests to your server. When they make a POST, PUT, PATCH or DELETE request to your application, the authentication cookie is not sent. As of August 2020, this protection is supported by 92% of modern browsers.
In addition, the framework provides token-based mitigation that works with either state (session tokens) or stateless (JWT). The client can read the CSRF token either from the HTML page (using a template) or from the XSRF-Token
cookie. Then, the token must be included in the X-XSRF-Token
header, the X-CSRF-Token
header or in the body with the _csrf
field in any POST, PUT, PATCH or DELETE request sent to the server (see examples).
#
Authentication with Session Tokens- YAML
- JSON
- JS
#
Authentication with JSON Web Tokens- YAML
- JSON
- JS
#
Examples#
Single-Page Applications (session tokens)#
Serverauth.controller.ts
api.controller.ts
#
ClientThe client must retrieve the CSRF token from the XSRF-Token
cookie and then send it in the X-XSRF-Token
header, the X-CSRF-Token
header or in the request body with the _csrf
field.
Most modern request libraries already handle it automatically for you using the X-XSRF-Token
header.
- Angular HttpClient
- Axios
- Native JavaScript
No additional configuration required.
No additional configuration required.
#
Single-Page Applications (JWTs)#
Serverauth.controller.ts
api.controller.ts
#
ClientSame as session tokens.
#
Regular Web Applications (session tokens)Regular Web Applications use Server-Side Rendering to generate their HTML pages.
#
Serverauth.controller.ts
view.controller.ts
api.controller.ts
#
Clientlogin.html
products.html
#
Advanced#
Increase stateless protection (JWT)In FoalTS, stateless CSRF protection is based on the double submit technique. CSRF tokens are generated randomly and signed with the JWT secret or RSA private key.
To increase the effectiveness of protection against sub-domain attacks, your auth JWT must include a unique subject
per user (usually the user ID) and an expiration date. The framework will then use these to create and sign the CSRF token.
#
Custom CSRF cookie nameThe name of the CSRF cookie can be changed in the configuration.
- YAML
- JSON
- JS