首页 > 解决方案 > 当 http 从 Angular 6 发布到 .netcore 2.0 webapi 时,跨域请求被阻止

问题描述

我正在尝试对我的 Angular 6 应用程序使用 Jwt 身份验证。尽管我将 cors 中间件添加到我的 .netcore 2 webapi 中,但我反复收到此错误消息

“跨源请求被阻止:同源策略不允许在http://localhost:5000/api/auth/login读取远程资源。(原因:CORS 请求未成功)。”

Angular6 http帖子:

angular6 http帖子

浏览器 cors 错误指示:

浏览器 cors 错误指示

.netcore2 webapi 中的 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();
            }
        }

标签: postasp.net-corecorsjwtangular6

解决方案


问题似乎是您正在发送 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 中间件注册是正确的


推荐阅读