Ich habe Probleme, Anfragen mit einem Bearer-Token von Angular (4) zu meinem Asp Net Core API zu machen.Anfrage (mit Autorisierung im Header) zu asp.net Core API von Angular 4 funktioniert nicht
Hier ist, wie ich es von Winkel tue:
Meine API Startup.cs Code:
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();
}
Aber ich erhalte die Unauthorized Fehler!
Ich habe viele Lösungen ausprobiert, die ich online gelesen habe, vor allem hier auf Stackoverflow (.NET Core UseCors() does not add headers, Enable OPTIONS header for CORS on .NET Core Web API und How to disable OPTIONS request?), konnte aber nicht an Würze bekommen! :( Als ich die Anfrage mit Postbote mache, ist es arbeiten.