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

10

41

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.

Gemstone answered 23/4, 2017 at 17:52 Comment(8)
JwtBearerMiddleware should produce a lot of log events. Add a logger in Startup.Configure method and check it.Ancestress
I found solution, problem was with middleware order :)Gemstone
@DiPix, It will be helpful if you post your answer here so that we can see what happened. Otherwise it is not helpful for others who lands on this page.Madonna
Every upvote on @Ray's comment should represent the people looking for what DiPix did. :|Known
@Known I posted the answer :)Gemstone
Please rename or remove this question, because answer you gave has nothing to do with debugging.Softspoken
I think you can check this answer https://mcmap.net/q/385464/-asp-net-core-jwt-authentication-always-throwing-401-unauthorizedSmaltite
In my case it was an issue with the JWT. Check the response headers for: WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"Babe
G
37

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

Gemstone answered 17/10, 2017 at 10:41 Comment(6)
If you're using ASP.NET Core 3.0 previews, swap UseMvc with UseRouting.Britt
In my case I forgot to add app.UseAuthentication() before app.UseMvc(), which is probably what the ConfigureAuth(app) above callsBowra
almost 2 years and I still got this!!Renaldorenard
@BaltzarMattson can you make a new answerCotsen
@Cotsen Unsure what a new answer will provide, just make sure the order is: app.UseAuthentication() then app.UseMvc()Bowra
@BaltzarMattson This answer is not obvious and someone has to read all the answers, then all the comments, and only then will they be able to understand. Up to you :)Cotsen
G
27

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://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0

Gaitskell answered 13/11, 2019 at 15:53 Comment(1)
After a few hours of research, this was the issue that I had... (on .net 6) my gosh. Thanks @GaitskellEtalon
T
7

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

Tahiti answered 3/11, 2019 at 17:20 Comment(1)
I think you got the order for 3.0 wrong. The correct order can be seen at - learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…Depend
E
4

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

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
Evocator answered 4/6, 2020 at 15:12 Comment(1)
This Answer already existed exactly above.Liaotung
P
3

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

    }
Pronucleus answered 1/10, 2019 at 8:41 Comment(0)
W
3

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
{
    ...
}
Wye answered 18/3, 2020 at 0:59 Comment(2)
Thank You! Thank You! Thank You! I previously had UseRouting() before UseAuthentication() and UseAuthorization(). This worked great while running it locally, but returned a 401 for everything once deployed to a web server. I saw answers saying I should have UseAuthentication() before UseRouting(), so I was trying to put UseAuthentication() and UseAuthorization() both before UseRouting() which did not work. Putting those three in the order you described above ended a day's worth of headache for me.Corena
Mark as answer please.Cumbrous
C
2

I fixes mine by changing the UseAuthentication() and order of UseAuthentication() and UseRouting() in the Configure method on Startup class.

Before

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

After

app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
Cornflower answered 19/6, 2022 at 18:9 Comment(0)
R
0

In my case i also was using app.MapWhen(code), and app.UseAuthentication(); should be before mapWhen like this

app.UseAuthentication();
app.MapWhen();
app.UseMvc();

Hope this will help.

Raseta answered 3/5, 2022 at 10:15 Comment(0)
P
0

Along with order of middlewares, parameters of token must be matched with Authentication parameters (specifically, secret key).

I made a mistake that I had used different secret keys in both places which was returning status code 401.

Sharing screenshots of code (.net core 3.1) that may assist any one.

Startup.cs > ConfigureServices() startup.cs file

Login Controller logic Token generation logic

Piggish answered 7/6, 2023 at 9:14 Comment(0)
R
-4

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

Ranunculus answered 11/6, 2018 at 23:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.