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

有些话、适合烂在心里 提交于 2020-01-02 00:31:07

问题


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:

Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6I...

to my method in controller decorated with [Authorize] attribute.

I receive 401 Unauthorized always... I saw comments bellow that tutorial and it seems that some people have similar issue also. I've no idea how I can solve this problem.


回答1:


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 ;)




回答2:


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

    }



回答3:


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




回答4:


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




回答5:


Solution for me was check the correctly order of middle-wares and other stuff in Configure method of Startup. Generally app.UseMvc();



来源:https://stackoverflow.com/questions/43574552/authorization-in-asp-net-core-always-401-unauthorized-for-authorize-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!