从 Angular 4 向 asp.net 核心 API 请求(使用 header 中的授权)不工作

Request (using authorization in header) to asp.net core API from Angular 4 not working

我正在努力使用不记名令牌从 Angular (4) 向我的 Asp 网络核心 API 发出请求。

这是我在 angular 中的做法:

我的APIStartup.cs代码:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  services.AddAuthentication();

  services.AddCors(options =>
  {
    options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .WithHeaders("authorization", "accept", "content-type", "origin"));
  });

  // Add the configuration singleton here
  services.AddSingleton<IConfiguration>(Configuration);

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  app.UseCors("CorsPolicy");
  app.UseOptions();
  app.Use(async (context, next) =>
  {
    await next();
    if (context.Response.StatusCode == 404 &&
       !Path.HasExtension(context.Request.Path.Value) &&
       !context.Request.Path.Value.StartsWith("/api/"))
    {
      context.Request.Path = "/index.html";
      await next();
    }
  });
  app.UseExceptionHandler(errorApp =>
  {
    errorApp.Run(async context =>
    {
      context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
      context.Response.ContentType = "application/json";

      var error = context.Features.Get<IExceptionHandlerFeature>();
      if (error != null)
      {
        var ex = error.Error;

        await context.Response.WriteAsync(ex.Message, Encoding.UTF8);
      }
    });
  });

  var jwtAuth = new JwtBearerOptions
  {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Authority = $"{Configuration["Authentication:AzureAd:AADInstance"]}{Configuration["Authentication:AzureAd:TenantId"]}",
    Audience = Configuration["Authentication:AzureAd:ClientId"],
    TokenValidationParameters =
            new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
              ValidIssuer = Configuration["Authentication:AzureAd:Issuer"]
            }
  };
  app.UseJwtBearerAuthentication(jwtAuth);


  app.UseMvcWithDefaultRoute();
  app.UseDefaultFiles();
  app.UseStaticFiles();
}

但我一直收到未经授权的错误!


我已经尝试了很多我在网上阅读过的解决方案,主要是在 Whosebug (, and ) 上,但无法解决问题! :( 当我使用邮递员发出请求时,它确实有效

好吧好吧..多么可怕的错误..我不敢相信我花了这么多时间试图解决这个问题! 问题出在电脑屏幕和椅子之间。我在错误的 angular 服务中添加了带有授权的 headers!!!