post - 当 http 从 Angular 6 发布到 .netcore 2.0 webapi 时,跨域请求被阻止
问题描述
我正在尝试对我的 Angular 6 应用程序使用 Jwt 身份验证。尽管我将 cors 中间件添加到我的 .netcore 2 webapi 中,但我反复收到此错误消息
“跨源请求被阻止:同源策略不允许在http://localhost:5000/api/auth/login读取远程资源。(原因:CORS 请求未成功)。”
Angular6 http帖子:
浏览器 cors 错误指示:
.netcore2 webapi 中的 Cors 中间件:
http后角
export class LoginComponent {
invalidLogin: boolean;
constructor(private router: Router, private http: HttpClient) { }
login(form: NgForm) {
let credentials = JSON.stringify(form.value);
this.http.post("http://localhost:5000/api/auth/login", credentials, {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
}).subscribe(response => {
let token = (<any>response).token;
localStorage.setItem("jwt", token);
this.invalidLogin = false;
this.router.navigate([""]);
}, err => {
this.invalidLogin = true;
});
}
}
Startup.cs 文件中的 Cors 中间件
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:5000",
ValidAudience = "http://localhost:5000",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(cfg=>cfg.AddPolicy("ClientDomain",builder=>builder.WithOrigins("http://localhost:4200")));
}
public void Configure(IApplicationBuilder app,IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseCors("ClientDomain");
app.UseMvc();
}
}
解决方案
问题似乎是您正在发送 HTTP 请求,但是您的 Cors 中间件在管道中注册较晚,并且从未调用过 HTTP 请求,因为
app.UseHttpsRedirection();
app.UseAuthentication();
换句话说:当您的请求在 http 上时,UseHttpsRedirection
中间件将短路管道并返回响应,在预检期间没有所需的 CORS 标头。如果您通过 https 执行此操作,同样适用,但用户未获得授权。
为了在 http(或重定向之前)以及未经授权的用户允许 CORS,您必须在上述行之前注册中间件
// now CORS is handled before https redirection & before authentication
app.UseCors("ClientDomain");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
永远记住,中间件是按照它们的注册(UseXxx
调用)顺序调用的。
琐事:当您获得任何中间件的异常时,异常中间件将清除标头。因此,抛出异常的方法将不包含 cors 标头,即使 cors 中间件注册是正确的
推荐阅读
- css - 在 PrimeNG 和 DataView 的 header 底部添加一个 div
- snowflake-cloud-data-platform - 有没有办法现在强制运行雪花的任务(在下一个预定的插槽之前)?
- android - Android 与 Google Drive API v3 的集成
- sql - 在 XML 中使用 2 CROSS APPLY
- python - ImportError:无法从应用程序导入名称 celery
- python-3.x - 来自 Keras 序列模型训练的 Nan 损失
- popup - 如何处理 Robot Framework 中的授权弹窗
- selenium - 关于 Selenium Webdriver 中隐式等待的问题
- android - 如何关闭这条看起来像对话框的消息?
- sql - 结果类似于 SQL Server 2016 中的 Oracle 查询