Search code examples
javascriptnode.jscsrfcsrf-protection

CSRF protection in singlepage web application


My Application structure as follows

1)API server running in api.mydomain.com

2)Frontend VUejs application running in www.mydomain.com

So i implemented authentication via httponly cookie.

But little confused with CSRF token implementation

Mysolution

1).CSRF token from the url like /getCSRF.

2) Store it in localstorage.

3) Send with every request.

But i don't think its the good way does anyone have suggestion?


Solution

  • First things first: Feel free to use session-based authentication in combination with the httpOnly (prevents your session cookie to be hijacked via XSS attack) cookie. Nothing wrong with that.

    After a certain action (e.g. login), generate a CSRF token and store it in a cookie (make it accessible to JavaScript). You can HMAC the token with server secret so that attacker cannot recreate a CSRF.

    Sure that CSRF will be sent as a cookie in each request, but the trick is to send it and expect it in a custom header (e.g. X-CSRF-HEADER). The final step is to check its validity.

    The key idea is that attacker cannot attach custom headers while performing a CSRF attack.