CORS Preflight request: The hidden story behind HTTP 401

Siranjeevi Mahendran
2 min readJan 7, 2021

What is CORS preflight request ?

A server is aware of using specific methods and headers. A CORS (Cross-Origin Resource Sharing) preflight request is a preliminary request that checks o see if the CORS protocol is understood. It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header. Before sending any actual request, the preflight request is fired (with the same endpoint but using the OPTIONS method) initially to check the permissions. If this got successful, then there will be a subsequent call with actual HTTP parameters. Most of the time, the preflight requests are fired without the authorization header even though it is present in the actual request. This causes the preflight request to get slapped by HTTP 401 (Unauthorized) response status.

Why I need to worry about this ?

If I have a back-end REST service deployed in Server A and the frontend Angular (React folks can react with their favorites ) service deployed in Server B, When the front-end attempts to make a call to the REST API, there comes CORS …

How can I avoid this preflight request failure ?

One can write a language-specific custom filter to accept all OPTIONS requests before the authentication. Although most of the modern back-end frameworks give features to enable CORS with few annotations, Some of the modern classics opt for writing their own custom CORS filter traditionally in their own language for various purposes.

Note : This may accept all OPTIONS request and It may potentially disrupt some of the security guidelines defined for the APIs by their owners.

--

--

Siranjeevi Mahendran

Programmer | Debugger | Beer lover | Weekend writer | Off-side Batsman | Mustang Rider | Fellow human