Search code examples
expresssecuritysessioncsrfexpress-session

Can CSRF attacks be blocked without CSRF tokens if I send the session-id in the headers


I'm using Session-based authentication in my app, and I want to protect against CSRF attacks I thought about just sending the session id in the header of the request.

To be clear the backed server will set the session id in a cookie but will validate the request against the id in the header. so the front end has to read the value of the cookie and send it in custom header

in that way no request will pass the security checkup without knowing the session id (the attacker can't relay on the browser to send it like the cookies).

is that considered as a bad practise or there's something that I'm missing here.


Solution

  • For this you would have to set the session id in a non-httpOnly cookie, which is against the traditional best practice.

    However, if you just call it a token, it magically becomes ok. :)

    Speaking seriously, you need to assess and accept (or not) the risk. You can generate your session id and return it in the response body upon login. It would behave like a token, you would probably store it in localStorage (or leave it in the cookie, which is even worse because cookies are sometimes stored as plain files in the client filesystem) and send it as a request header. It would be accessible by javascript, meaning it would be susceptible to potential xss. The same is true for any token-based authentication. This would effectively mitigate csrf, and is a usual thing to do.

    However, exchanging csrf for xss when you don't actually need a token-based solution does not sound like a good deal. You will have xss in your app if it grows big enough. The best possible place for request authentication info (ie. a session id) is a httpOnly cookie so that it's protected against xss. Then of course you need separate csrf protection.

    The only scenario where you would use tokens is if you need to send the token to multiple origins (eg. multiple apis on different domain), or in a single sign-on scenario where the identity provider and service providers are different. Cookies cannot do this.

    So if you don't need tokens, it's best to avoid the higher risk xss (at least for the session id) and implement separate csrf protection.