I have the following system in place on my web app and I'd like to know if it's secure.

  1. Cookie contains CSRF token.
  2. Application detects CSRF token in cookie.
  3. Application places token in a header.
  4. Token in header is verified by the server.

I have not seen any definitive information on whether or not it's okay to use cookies as a place to store CSRF tokens. Please enlighten me.

EDIT: More detail - Angular looks for a CSRF token in the cookies, and when it finds one, it adds a header with this value. Then the server determines if the header value is legitimate.


2 Answers 2


I don't see any flaw in the method and I think it can be used to protect against CSRF. There is just one small issue: This method will work just fine as long as the cookie storing the CSRF token is NOT set as HTTPOnly. The problem is with this requirement:

Application detects/places token.

This implementation is similar to Double Submit Cookies. Double submitting cookies is defined as sending a random value in both a cookie and as a request parameter, with the server verifying if the cookie value and request value are equal. The benefit of using this method is that the application does not have to save this value in any way.

Since your implementation requires the cookie value to be read via client-side scripting (JavaScript) and then placed as a request header, it can break application functionality if it is set as HttpOnly (which prevents JavaScript from reading its value) at any point in future.

  • There are also downsides of this method. Example: Subdomains within a site will be able to set cookies on the client for the whole domain See docs.djangoproject.com/en/1.8/ref/csrf for more details. For additional protection, you should also check referrer to ensure it's indeed coming from your domain. Though, it's not required as long as you don't allow cross-domain requests. Jul 9, 2015 at 20:21

Yes, adding a custom header, even without a token and using a static one such as X-Requested-With: XMLHttpRequest inherently protects against CSRF because custom headers can't be passed cross-domain without enabling CORS on the server.

If there's a one-to-one relationship from your UI domain to your API domain (or that they are the same domain), then adding any custom header will mitigate CSRF.

If you're planning on using your API to serve multiple, possibly untrusted, websites then you would need to ensure that one of the websites you are supporting cannot make API requests on the behalf of another one, therefore your token approach in a header is better suited to that. The token can then be validated to ensure that it matches both the user session and that it has a valid API key from the website being utilised for the front-end. However, this would better fit the Synchronizer Token Pattern model rather than Double Submit Cookies.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .