Search code examples
haskellcorsservant

Configure correctly CORS with wai-cors


I am struggling with Servant and the CORS configuration: I am exposing and API through Servant and I have the following configuration:

-- Wai application initialization logic
initializeApplication :: IO Application
initializeApplication = do
  let frontCors = simpleCorsResourcePolicy { corsOrigins = Just ([pack "https://xxxx.cloudfront.net"],  True)
                                           , corsMethods = ["OPTIONS", "GET", "PUT", "POST"]
                                           , corsRequestHeaders = simpleHeaders }
  return
    $ cors (const $ Just $ frontCors)
    $ serve (Proxy @API)
    $ hoistServer (Proxy @API) toHandler server

When I perform a query like this through Chromium (by copying and pasting):

curl 'https://api.xxx/' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Referer: https://xxx.cloudfront.net' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36' \
  -H 'Authorization: Bearer XXX==' \
  --compressed

It works but if I copy-paste the fetch query in the dev console:

fetch("https://api.xxx", {
  "headers": {
    "accept": "application/json, text/plain, */*",
    "authorization": "Bearer XXX=="
  },
  "referrer": "https://xxx.cloudfront.net/",
  "referrerPolicy": "no-referrer-when-downgrade",
  "body": null,
  "method": "GET",
  "mode": "cors",
  "credentials": "include"
});

I get:

> Access to fetch at 'https://api.xxx' from origin 'https://xxx.cloudfront.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
polyfills-es2015.3eb4283ca820c86b1337.js:1 GET https://api.xxx net::ERR_FAILED
e.fetch @ polyfills-es2015.3eb4283ca820c86b1337.js:1
>  (anonymous) @ VM20:1
> x:1 Uncaught (in promise) TypeError: Failed to fetch

Any hints regarding that? Especially why it works in cUrl and not in Chromium? Thanks in advance.


Solution

  • It was a basic CORS issue, in fact, sending Authorization without having it in the corsRequestHeaders makes the request rejected.

    I should have written:

    , corsRequestHeaders = ["Authorization", "Content-Type"]