Search code examples
authenticationcookiescsrf

Why are auth cookies susceptible to CSRF while auth tokens are not


I have been reading about cookies, local and session storage, and how it all relates to authentication.

One thing I have been reading is that API's generally do not have to be as worried about CSRF as web apps (except for flash related vulnerabilities?) and the reason has something to do with cookie based auth vs token based auth.

What I don't understand is why a cookie is easier to ride than a token. Is it because the cookies are sent automatically based on the domain of the request where as some sort of manual effort is required to send the token. Is that last statement even correct?

I think one reason I am confused is because the frameworks I use always seem to implement this stuff on their own so I have never had to dig in to implement it.


Solution

  • Yes, a CSRF attack happens when you are visiting a malicious site and that site triggers a request to a legitimate website that the browser will implicitly authenticate.

    For example, if you are still logged into your email provider using a cookie based authentication mechanism and you happen to visit a malicious site that executes a request from its JavaScript to https://www.youremailprovider.com/inbox, then the browser will automatically attach the cookies it has stored for that domain to the request. Now, the JavaScript from the malicious site just got access to all the emails in your inbox.

    Token based authentication is not vulnerable to this type of attack as the attacker site would first need to steal the token before it can make the AJAX call to the legitimate website.