【发布时间】:2018-06-09 11:08:45
【问题描述】:
我目前有一个独立于我的 .net core 2 web api 的 angular 应用程序 web 客户端。 Angular 应用程序托管在 localhost:35000,而 Web api 托管在 localhost:36000。因此,有很多地方我需要允许 CORS 以使请求成功。在Startup.cs中,我的认证中间件配置如下:
services.AddOpenIddict(options =>
{
// Integrate with EFCore
options.AddEntityFrameworkCoreStores<MylestoneIdentityContext>();
// Use Json Web Tokens (JWT)
options.UseJsonWebTokens();
// Set a custom token endpoint (default is /connect/token)
options.EnableTokenEndpoint(Configuration["Authentication:OpenIddict:TokenEndPoint"]);
// Set a custom auth endpoint (default is /connect/authorize)
options.EnableAuthorizationEndpoint(Configuration["Authentication:OpenIddict:AuthorizationEndPoint"]);
// Allow client applications to use the grant_type=password flow.
options.AllowPasswordFlow();
// Enable support for both authorization & implicit flows
options.AllowAuthorizationCodeFlow();
options.AllowImplicitFlow();
// Allow the client to refresh tokens.
options.AllowRefreshTokenFlow();
// Disable the HTTPS requirement (not recommended in production)
options.DisableHttpsRequirement();
// Register a new ephemeral key for development.
// We will register a X.509 certificate in production.
options.AddEphemeralSigningKey();
});
...
app.UseAuthentication();
并且我已允许对我的应用程序的 CORS 请求如下:
services.AddCors(options =>
{
options.AddPolicy("AllowCors",
builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
...
app.UseCors("AllowCors");
...
//also put [EnableCors("AllowCors")] on each controller class declaration
我可以访问服务器并成功注册用户帐户,但是尝试登录时,我仍然在浏览器中收到错误消息:
Failed to load http://localhost:36000/api/connect/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:35000' is therefore not allowed access. The response had HTTP status code 500.
我认为这可能是由于 /api/connect/token 没有实际的控制器类,我可以将注释 [EnableCors("AllowCors")] 放在上面。我尝试了多种方法来克服这个问题,包括在我的网络客户端中将指定的标头添加到我的请求中,如下所示:
return this.http.post(
url,
this.toUrlEncodedString(data),
new RequestOptions({
headers: new Headers({
"Content-Type": "application/x-www-form-urlencoded",
"Access-Control-Allow-Origin": "*"
})
}))
命中以下有角度的 http 服务包装器:
post(url, data, opts = {}) {
this.configureAuth(opts);
return this.http.post(url, data, opts);
}
configureAuth(opts: any) {
var i = localStorage.getItem(this.authKey);
if (i != null) {
var auth = JSON.parse(i);
console.log(auth);
if (auth.access_token != null) {
if (opts.headers == null) {
opts.headers = new Headers();
}
opts.headers.set("Authorization", `Bearer ${auth.access_token}`);
opts.headers.set("Access-Control-Allow-Origin", `*`);
}
}
}
关于如何允许此授权请求通过我的中间件,我已经没有想法了。感谢所有帮助。
【问题讨论】:
-
可能不是唯一的问题,但我认为您还需要将 .AllowCredentials() 添加到您的 CORS 策略中,否则它不会接受您在客户端设置的授权标头。哦,在调用 app.UseMvc() 之前,请仔细检查您是否设置了 cors 政策。
标签: angular asp.net-core authorization asp.net-core-2.0