0

I have an ASP.NET Core API project running on my local IIS, and a client website running on development environment (http://localhost:53559). The API has a protected resource that I want to call with an authorization header.

On my ASP.NET API I've enabled CORS using:

services.AddCors();
app.UseCors(builder => builder.AllowAnyOrigin());

My ajax call looks like this:

$.ajax({
    type: "GET",
    url: "http://localhost/MyApi/api/values",
    async: true,
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.withCredentials = true;
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});

If I don't include a header in the request then I'm getting a 401 response as expected. And when looking at the request with Fiddler this is what I see in the request:

GET http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Accept: */*
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36     (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6

But when I add my authorization header, I'm getting a 204 response and this is what I have on the request (which off-course doesn't work and doesn't look at all like a request I'm expecting to get - not GET call, no authorization header....):

OPTIONS http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36     (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6

I'm using IdentityServer to handle authentication.

What am I missing here? why can't I send headers with the request?

developer82
  • 13,237
  • 21
  • 88
  • 153
  • Possible duplicate of [AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?](https://stackoverflow.com/questions/21783079/ajax-in-chrome-sending-options-instead-of-get-post-put-delete) – moritzg Jun 08 '17 at 08:43

1 Answers1

0

I've added the following to my web.config and it worked:

<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
developer82
  • 13,237
  • 21
  • 88
  • 153