Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug problems in [Authorize] attribute

The problem

That's everything in the title, really. I have an [Authorize] attribute that's always returning 401 and I don't know why. How can I step through the logic behind it?

A little more detail

I'm trying to use Azure AD authorization via JWT tokens. I've done this successfully with other projects, so I'm sure the problem is some minor configuration issue, but as far as I can tell, the only interaction I get to have with [Authorize] is in Startup.cs, where I have this:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
        TokenValidationParameters = new TokenValidationParameters
        {
            ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
            SaveSigninToken = true,
        },
        Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
    });

But that bit only runs when the application starts. Otherwise, [Authorize] is kind of a black box to me.

Thanks for the help!

like image 465
crowhill Avatar asked Dec 05 '25 02:12

crowhill


1 Answers

try put breakpoint in OnAuthenticationFailed method of JwtBearerEvents class, there you can read exception message and then set your config accordingly

.AddJwtBearer(options =>
            {
                options.Authority = Configuration["OIDC:Authority"];
                options.Audience =  Configuration["OIDC:Audience"];
                options.RequireHttpsMetadata = true;
                options.TokenValidationParameters = new 
                TokenValidationParameters()
                {
                    ValidIssuer = Configuration["OIDC:Issuer"]                        
                };
                options.Events = new JwtBearerEvents
                {                        
                    OnAuthenticationFailed = async ctx => 
                     {
                         var putBreakpointHere = true;
                         var exceptionMessage = ctx.Exception;
                     },
                };
            });
like image 138
Lukáš Belák Avatar answered Dec 07 '25 20:12

Lukáš Belák



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!