What is wrong with my Startup.ConfigureServices that is causing JWT Bearer authentication not to work?

Viewed 58

I have been trying to implement "PwdLess" as a simple passwordless authentication mechanism for my ASP.Net Core 2.2 application. It is successfully generating JWTs which I am trying to use on the backend API of my application, with the JWT passed in via Authorization: Bearer <token>.

In my Startup.ConfigureServices method, I have the following code:

            // JWT authentication
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                 {
                     options.TokenValidationParameters = new TokenValidationParameters

                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = "MYISSUERSTRINGHERE"
                        ValidAudience = "MYAUDIENCESTRINGHERE"
                        IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes("MYSECRETHERE"))
                    };
                });

            // ASP.NET Core MVC 
            services.AddMvc();

In the controller, on the method I want to authorize access to, I have:

        [Authorize]
        public IActionResult SomeMethod()
        {
        }

This throws a 401, which is confusing... Even more so because if I use the following code in my controller instead, everything works as expected:

        [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        public IActionResult ValidateToken()
        {
        }

I don't understand what I'm missing from my Startup.ConfigureServices that makes the AuthenticationSchemes value necessary on my Authorize attribute!

Please can you shed some light on the error of my ways?

1 Answers

As per the above comments, apart from the authentication services, we need also enable the Authentication middleware before UseMvc() (as well as any other middlewares that want to access HttpContext.User):

app.UseAuthentication();
app.UseMvc();
Related