What is CSRF
Please jump to this article to learn more details:
What we always do in prod to prevent CSRF
1. CSRF middleware
Technique background:
1. frontend: angular
2. backend: nodejs
Angular CSRF
Actually Angular provide csrf service by default: https://angular.cn/best-practices/security#httpclient-xsrf-csrf-security
It will get csrf token from cookie, with the key: XSRF-TOKEN
Then provide a default interceptor to add it into request header with the key:
X-XSRF-TOKEN
Middleware CSRF
There are some csrf third-party package we can use.
For example, csrf, csurf...
The whole validation process we usually do
1. When login / GET request, this time there is no csrf in the cookie, the csrf middleware will create a new csrf token, with a name in agreement, for example, setCookie('Test.csrf', 'newcsrfctoken', { secure: true })
a. hash('newcsrfctoken') to a new hashcode, maybe we can call it 'newcsrfhashcode'
b. setCookie('XSRF-TOKEN', 'newcsrfhashcode')
c. setHeader('X-XSRF-TOKEN', 'newcsrfhashcode')
d. next() to backend
2. When it is a POST request, we usually check if there is a Test.csrf in the cookie: a = cookie['Test.csrf']
a. b = header['x-xsrf-token'], in my testing, it should be lowercase
c. if a === b(hash comparision), means it is our same origin request, because we find the same token in the header.
d. if can't find b or it is not equal, will raise a CSRF error
2. Same Origin Policy
So what is same-origin-policy: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
Cookie attribute overview
We all have seen the code like this:
res.cookie('***', token, { secure: true })
What exactly the `secure` means here?
If secure is true when setting the cookie, it means only https protocol will use this cookie.
For others:
httpOnly: client can't read or change this cookie
domain: only request from this domain will take this cookie
sameSite:
1. Strict: can't send request from the different site
2. Lax: not sure....
3. None: if the cookie can be set to secure, it can break the SOP rule
3. More experiment
I try to raise a CSRF request by typing the follwing code:
const data = JSON.stringify({});
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener('readystatechange', function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open(
'POST',
'https://',
);
xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Content-type', 'application/ecmascript');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
I login to the website first, so that the cookie will have my auth token inside.
I will send the request in another website:
But got this issue: seems the chrome will block all third-party cookie to cross-site:
https://goo.gle/3pcd-dev-issue
And I check the cookie list of this request, seems it will only send the cookie with secure is true and saemsite is NONE: