-1

This answer states, that one way X-Requested-With header prevents CSRF attacks is that if server doesn't allow it then a modern browser wont allow javascript code to add this header. And if header is present server can be sure that request didn't originate from another page a user might have opened.

To my understanding the way browser determines whether a custom header is allowed or not in an ajax request is by making a preflight request. And then a server responds with header Access-Control-Allow-Headers. Which contains list of headers allowed for a request in question. So if servers returns an empty list then CORS ajax calls couldn't have xhr header present. Indicating different origin.

So my question is whether preflight request is triggered if origin is the same. Because if they are, then server would say dont add any header, and if browser doesn't then to server a request from its own origin would be indistinguishable from another origin.

Muhammad Umer
  • 14,722
  • 14
  • 69
  • 139

1 Answers1

1

So my question is whether preflight request is triggered if origin is the same.

No, it isn't.

Because if they are, then server would say dont add any header, and if browser doesn't then to server a request from its own origin would be indistinguishable from another origin.

The browser not sending a preflight request doesn't stop the server from testing the actual request for a header and throwing an error if it isn't present.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • I meant if preflight was sent then it'd forbid adding any headers and even request originating my own domain/page would be blocked from adding xhr header. Since you said they aren't this wont be a problem. Basically CORS will say dont add any headers and my code will add xhr header, thus, any api request will need to have xhr header if not then it's unsafe request. Thanks. Is there a source that verifies preflight isn't triggered just for the sake completeness – Muhammad Umer Apr 17 '21 at 20:04
  • "Basically CORS will say dont add any headers and my code will add xhr header, thus, any api request will need to have xhr header if not then it's unsafe request." — That won't help you against CSRF attacks, which are same origin in nature. – Quentin Apr 17 '21 at 20:07
  • https://fetch.spec.whatwg.org/#main-fetch — Step 12 – Quentin Apr 17 '21 at 20:10