【发布时间】:2017-11-09 19:19:03
【问题描述】:
我有一个在本地 IIS 上运行的 ASP.NET Core API 项目,以及在开发环境 (http://localhost:53559) 上运行的客户端网站。 API 有一个受保护的资源,我想用授权标头调用它。
在我的 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);
}
}
});
如果我没有在请求中包含标头,那么我将按预期收到 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
但是,当我添加我的授权标头时,我收到了 204 响应,这就是我在请求中的内容(偏离路线不起作用,看起来一点也不像我期待的请求获取 - 不是 GET 调用,没有授权标头....):
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 来处理身份验证。
我在这里缺少什么?为什么我不能随请求一起发送标头?
【问题讨论】:
标签: jquery ajax asp.net-core identityserver4 asp.net-core-webapi