Author : HASSAN MD TAREQ | Updated : 2020/08/01
CSRF and anti-forgery token
When a user login once, the server sets a authentication (session) cookie to authenticate for subsequent requests. The seesion cookie can be compromised (hacker can hijack your authentication cookie and used it to gain access). Therefore frameworks (ASP.NET Core, Spring) uses CSRF token. When a request is made, framework checks if the request coming from the same user by checking both the session cookie and CSRF token.
where does CSRF token come from?
When the user logs in, framework puts a CSRF token (randomly generated token) to the view. From the next calls to the server, browser send that CSRF token (+ session cookie) to the server.
When to use anti-forgery token
When using session based authentication - mainly in web app. API can also use CSRF but API is meant to be CORS.
Issues when using CSRF
1. Static files (i.e. bootstrap, jquery etc.)
When CSRF is used, the browser gonna refuse to accept resources (i.e. bootstrap, jquery etc.) from other sites (Same origin policy). You can use setting to allow those static files to load from different origin (i.e. CDN)
Ajax calls will be rejected, so you have to put CSRF token value (
$('token').val()) in every request.