Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute

前端 未结 7 1148
陌清茗
陌清茗 2021-01-07 18:22

For the first time I\'m creating Authorization in ASP.NET Core. I used tutorial from here TUTORIAL

The problem is when I sending request from postman:



        
相关标签:
7条回答
  • 2021-01-07 19:05

    If you are using ASP.NET Core 3.0

    Check this order

    app.UseAuthentication();

    app.UseRouting(); //must be below app.UseAuthentication();

    If you are using ASP.NET Core < 3.0

    Just replace the app.UseRouting(); by app.UseMvc();

    i.e:

    app.UseAuthentication();

    app.UseMvc(); //must be below app.UseAuthentication();

    0 讨论(0)
  • 2021-01-07 19:09

    in ASP.NET Core 3.0, i had the same problem, what worked for me was:

    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    

    in StartUp.Configure method.

    This doc shows typical ordering of middleware components: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0

    0 讨论(0)
  • 2021-01-07 19:20

    At the request of others here is the answer:

    The problem was with the middleware order in Startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ConfigureAuth(app); // your authorisation configuration
    
        app.UseMvc();
    }
    

    Why middleware order is important? If we put app.UseMvc() first - then the MVC actions would get in the routing and if they see the Authorize attribute they will take control of its handling and that's why we receives 401 Unauthorized error.

    I hope it helps someone ;)

    0 讨论(0)
  • 2021-01-07 19:23

    In my case I was following coreApi,angularClient tutorial, but getting unauthorized error every time also In my case angular application is running under Core Api project.

    So then I changed the order like this and it works now

       public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
        {
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
    
    
            app.UseAuthentication();
    
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
    
    
            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501
    
                spa.Options.SourcePath = "ClientApp";
    
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
    
    
             loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
    
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
    
        }
    
    0 讨论(0)
  • 2021-01-07 19:24

    My ConfigureServices and Configure methods (Asp.Net Core 3.1.0) in the Startup class:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("AllowsAll", builder =>
            {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            });
        });
    
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            ...
        });
    
        services.AddControllers();
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
    
        app.UseAuthentication();
        app.UseRouting();
        app.UseAuthorization();
    
        app.UseCors(options => options.AllowAnyOrigin());
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
    

    My controller:

    [Authorize]
    [EnableCors("AllowsAll")]
    [Route("[controller]")]
    public class MyController : MyController
    {
        ...
    }
    
    0 讨论(0)
  • 2021-01-07 19:27

    for .NET CORE 3.0 or higher user this order in "configure" located in StartUp.cs

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
    
    0 讨论(0)
提交回复
热议问题