Search code examples
resthttpcsrf

Is It OK To Use ONLY (CSRF) Tokens For Authentication


Recently, I've learned that cookies are sent automatically with every request. And this behaviour makes some websites vulnerable to CSRF. From what I've learned, CSRF can be prevented by using CSRF tokens that are stored in the client's JavaScript or Storage APIs, but NOT in the cookies (to prevent it from being sent too).

My question is, if I would have an authentication cookie and a CSRF token, why not just use tokens instead of cookies? Why not rely only on tokens that are not stored in the cookies?

Can I remove cookie authentication from my application and let the client just send a token in the headers or something like that (maybe X-Authentication-Token).

I think this approach has many advantages, like not having to store and manage two UUIDs on the database, and not having to send the CSRF token in the body. What do you think?


Solution

  • You can use an authentication token and not put in the cookie header. The logical place is the Authorization header. It's no longer a CSRF token, but it's certainly good authentication and used a lot by different APIs.

    There are some security trade-offs. One benefit of using a cookie is that you can mark it as 'HTTPOnly' which makes it invisible to Javascript.

    I would generally recommend looking at a standard like OAuth2 instead of doing something from scratch yourself.