Search code examples
c#angularapiasp.net-coreauth0

API call: "Endpoint ... contains authorization metadata, but a middleware was not found that supports authorization."


I am currently working on creating a simple web application in angular using Auth0 to offload the authorization portion. Right now I am trying to connect the front end portion and the backend portion and I am having some trouble.

For some reason when I send a https request to the API it keeps giving me the following error in the chrome console.

Access to XMLHttpRequest at 'https://localhost:5001/api/private' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So I went to use postman to try and access the api. I got past the CORS part error but instead het Endpoint .... contains authorization metadata, but a middleware was not found that supports authorization.

This is what my startup class looks like in my backend:

public class Startup
{
    readonly string MyAllowSpecificOrigins = "localhost_origin";

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)
    {
        string domain = $"https://{Configuration["Auth0:Domain"]}/";
        services.AddControllers();

        // 1. Add Authentication Services
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Authority = domain;
            options.Audience = Configuration["Auth0:ApiIdentifier"];
            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = ClaimTypes.NameIdentifier
            };
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
        });

        services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();

        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("https://localhost:4200").AllowAnyMethod().AllowAnyHeader();
                });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }



        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors();
        app.UseAuthentication();
        //app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });


    }
}

Here is my test controller that I call the api on:

[Route("api")]
public class TestController : Controller
{
    [HttpGet]
    [Route("private")]
    [Authorize]
    public IActionResult Private()
    {
        return Json(new
        {
            Message = "Hello from a private endpoint! You need to be authenticated to see this."
        });
    }
}

I've read the documentation and followed the examples on auth0's sites for implementing this. I can't quite find where I went wrong.


Solution

  • Okay for the people that might run into a similar issue. It ended up being a problem of the order of things in the startup.cs file and making my localhost origin use http instead of https. I wasn't able to deduce this from the tutorial article because they ommitted a lot of code. I ended up having to download the sample project and compare line by line. This is the final startup.cs file that worked for me:

    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "localhost_origin";
    
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
    
        public void ConfigureServices(IServiceCollection services)
        {
            string domain = $"https://{Configuration["Auth0:Domain"]}/";
            services.AddControllers();
    
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                    builder =>
                    {
                        builder
                            .WithOrigins("http://localhost:4200")
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                    });
            });
    
            // 1. Add Authentication Services
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority = domain;
                options.Audience = Configuration["Auth0:ApiIdentifier"];
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = ClaimTypes.NameIdentifier
                };
            });
    
            services.AddAuthorization(options =>
            {
                options.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
            });
    
            services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
    
    
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
    
            app.UseHttpsRedirection();
    
            app.UseRouting();
    
            app.UseCors(MyAllowSpecificOrigins);
    
            app.UseAuthentication();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
    
    
        }