jQuery - 无法通过授权 header 执行 ajax 请求

jQuery - unable to execute ajax request with authorization header

我在本地 IIS 上有一个 ASP.NET 核心 API 项目 运行,在开发环境 (http://localhost:53559) 上有一个客户端网站 运行。 API 有一个受保护的资源,我想通过授权 header.

调用它

在我的 ASP.NET API 上,我使用以下方式启用了 CORS:

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

我的 ajax 电话是这样的:

$.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);
        }
    }
});

如果我没有在请求中包含 header,那么我将收到预期的 401 响应。当使用 Fiddler 查看请求时,这是我在请求中看到的内容:

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

但是当我添加我的授权 header 时,我收到了一个 204 响应,这就是我在请求中得到的(off-course 不起作用并且不查看都像我期望得到的请求——不是 GET 调用,没有授权 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

我正在使用 IdentityServer 来处理身份验证。

我在这里错过了什么?为什么我不能随请求发送 headers?

我已将以下内容添加到我的 web.config 并且有效:

<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />