2

I am struggling to make requests using a bearer token from Angular (4) to my Asp Net core API.

Here is how I am doing it from angular:

enter image description here

My 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();
}

But I keep getting the Unauthorized error!

enter image description here
enter image description here

I have tried many solutions that I've read online, mostly here on stackoverflow (.NET Core UseCors() does not add headers, Enable OPTIONS header for CORS on .NET Core Web API and How to disable OPTIONS request?), but couldn't get it to wort! :( When I make the request using postman, it does work.

Ewertonews
  • 349
  • 3
  • 16

1 Answers1

1

Ok Ok .. what a terrible mistake.. I can't believe that I spent so much hours trying to figure this out! The problem was between the computer screen and the chair.. I was adding the headers with the Authorization in the wrong angular service!!!

Ewertonews
  • 349
  • 3
  • 16