Currently, my architecture as follows.

  • API is served from api.domain.com.
  • Frontend application is served from frontend.domain.com.

I'm concidering two different methods for CSRF protection:

  1. Letting the frontend acquire a CSRF token by making a request to api.domain.com/getCSRF after it loads the first time.
  2. Enable CORS on my api.domain.com and allow request only from frontend.domain.com.

I found a major website using my first approach to get the CSRF token, but I don't think it's a good approach. Which one of my methods is better for CSRF protection?

1 Answer 1


You would need both:

  • Just #1 alone, without any CORS policy, would not allow the frontend to read the responses. And if you set a to generous CORS policy, it would allow anyone included in it to CSRF you.

  • Just #2 alone would not offer CSRF protection. You do not need CORS permission to send normal non-preflighted requests, such as submitting an ordinary form. Attacks could still be mounted from any domain. CORS does not protect against CSRF because it's not designed to.

Together they work. The token ensures that only "non-forged" requests are allowed, and the CORS policy ensures that only the frontend can get it's hands on the token.

I should also mention that in situations like this, with an API serving a frontend, CSRF protection often comes "automatically" because a bearer token in the auth header (as opposed to a cookie) is used. So if that's your authentication scheme, you may already be protected. Implementing another layer of defence on that doesn't hurt, though.

  • " Attacks could still be mounted from any domain" but if maid request with curl what happens here Apr 4, 2018 at 8:58
  • @iambatman Remember that in a CSRF attack, it is the victims browser that sends the "forged" request. CURL is not relevant.
    – Anders
    Apr 4, 2018 at 10:58
  • @Yes your assumption was correct one more doubt Apr 4, 2018 at 11:00
  • "because a bearer token in the auth header is used"I am using the same way but the auth cookie is not exposed to javascript instead i am sending it with each request Apr 4, 2018 at 11:03
  • @iambatman If you are using a cookie, you need explicit CSRF protection. Cookies, unlike header values, are sent automatically by the browser.
    – Anders
    Apr 4, 2018 at 12:05

You must log in to answer this question.

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