Search code examples
asp.net-coredebuggingjwtauthorize

How can I determine why a bear token failed


Running a basic ASP.NET Core RESTful server, I'm having my endpoint secured using a JWT token that I provide on an endpoint (this is a proof of concept for the moment). When I test using Postman, I am able to authenticate properly, however, coming from a console app, getting 401, Unauthorized.

Here is what I have in a ServiceExtensions class:

public static IServiceCollection ConfigureJwtAuthentication(this IServiceCollection services,
            IConfiguration config)
        {
            var section = config.GetSection("Jwt");
            var jwtOptions = section.Get<JwtConfigOptions>();

            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

                })
                .AddJwtBearer(options =>
                {
                    //options.Authority = jwtOptions.AuthorityUrl;
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = jwtOptions.Issuer,
                        ValidAudience = jwtOptions.Audience,
                        IssuerSigningKey = jwtOptions.SymmetricSecurityKey
                    };
                });

            return services;
        }

This is my JwtConfigOptions class:

public class JwtConfigOptions
    {
        public string Key { get; set; }
        public string Issuer { get; set; }
        public string Audience { get; set; }
        public string AuthorityUrl { get; set; }
        public string AudienceUrl { get; set; }
        public SymmetricSecurityKey SymmetricSecurityKey => new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key));
    }

And have the values in appsettings.json, so I'm using the same values for creating as vetting the token.

Is there any way to log why a given token is being rejected?


Solution

  • I was able to find an answer. I found this site which had link to a github solution that had the source code for the projects in the Microsoft.AspNetCore.Authentication.JwtBearer assembly. I attached to the JwtBearerHandler project and was able to step through the code. Turns out I encoded the bearer token incorrectly in the header. Actually had the correct code commented out the line before /redface