0

I'm new to JWT and ASP.NET Core 6 Web API and I'm trying to add authentication to an endpoint.

When I paste the bearer token in the Authorization header in Postman and run a controller action with [Authorize], I still get a 401 Unauthorized error.

AuthenticationController:

[HttpPost]
public ActionResult<string> Authenticate([FromBody] AuthenticationRequestBody request)
{
    if (!ModelState.IsValid)
    {
        return Unauthorized();
    }

    // validate the credentials
    var user = ValidateUser(request.UserName!, request.Password!);

    if (user == null)
    {
        return Unauthorized();
    }

    /*--- creating a token ---*/

    // create security key
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:SecretForKey"]));

    // create signing credentials
    var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    // create claims for token
    var claimsForToken = new List<Claim>
        {
            new Claim("sub", user.UserId.ToString()), //sub is a standardized key for the unique user identifier
            new Claim("given_name", user.Name),
        };

    // create token
    var jwtSecurityToken = new JwtSecurityToken(
            _configuration["Authentication:Issuer"],    // entity that created the token
            _configuration["Authentication:Audience"],  // entity for whom the token is intended to be consumed
            claimsForToken,                             // claims containing user info
            DateTime.UtcNow,                            // dateTime that indicates the start of token validity (before this time, the token cannot be used and validation will fail)
            DateTime.UtcNow.AddHours(1),                // dateTime that indicates the end of token validity (after this time, the token is also invalid and validation will fail)
            signingCredentials                          // with security algorithm
        );

    // serializers the JWTSecurityToken into a string that is returned
    var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

    return Ok(token);
}

Note: /Authenticate endpoint is not connected to the database yet and it just calls ValidateUser() which returns a constant object just for testing.

Here is my Program.cs:

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Authentication:Issuer"],
            ValidAudience = builder.Configuration["Authentication:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretForKey"])
            )
        };
    });

Here is the request pipeline:

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Note that the Authentication configuration is in my secrets.json


Upon testing the /Authenticate endpoint using Postman and attaching the Authorization header with the Bearer {token} format, and subsequently calling an action with the [Authorize] attribute, I consistently get a 401 Not Authorized response. The WWW-Authenticate header indicates an error of Bearer error="invalid token".

When I make the POST request, I get this log:

2023-08-10 21:42:10.692 +08:00 [DBG] AuthenticationScheme: Bearer was not authenticated.

I also noticed this logged error in the GET:

2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
System.MissingMethodException: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken& signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
2023-08-10 21:42:21.912 +08:00 [INF] Bearer was not authenticated. Failure message: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
2023-08-10 21:42:21.918 +08:00 [INF] Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
2023-08-10 21:42:21.930 +08:00 [INF] AuthenticationScheme: Bearer was challenged.

Here are the logs for the POST:

2023-08-10 21:42:10.557 +08:00 [INF] Request starting HTTP/1.1 POST https://localhost:7288/api/authentication application/json 99
2023-08-10 21:42:10.571 +08:00 [DBG] 1 candidate(s) found for the request path '/api/authentication'
2023-08-10 21:42:10.583 +08:00 [DBG] Endpoint 'Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)' with route pattern 'api/authentication' is valid for the request path '/api/authentication'
2023-08-10 21:42:10.583 +08:00 [DBG] Request matched endpoint 'Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)'
2023-08-10 21:42:10.585 +08:00 [DBG] Static files was skipped as the request already matched an endpoint.
2023-08-10 21:42:10.692 +08:00 [DBG] AuthenticationScheme: Bearer was not authenticated.
2023-08-10 21:42:10.695 +08:00 [INF] Executing endpoint 'Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)'
2023-08-10 21:42:10.765 +08:00 [INF] Route matched with {action = "Authenticate", controller = "Authentication"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.ActionResult`1[System.String] Authenticate(Notify.API.Controllers.AuthenticationRequestBody) on controller Notify.API.Controllers.AuthenticationController (Notify.API).
2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of authorization filters (in the following order): ["None"]
2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of resource filters (in the following order): ["None"]
2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of action filters (in the following order): ["Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter (Order: -3000)","Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter (Order: -2000)"]
2023-08-10 21:42:10.768 +08:00 [DBG] Execution plan of exception filters (in the following order): ["None"]
2023-08-10 21:42:10.768 +08:00 [DBG] Execution plan of result filters (in the following order): ["Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter (Order: -2000)"]
2023-08-10 21:42:10.768 +08:00 [DBG] Executing controller factory for controller Notify.API.Controllers.AuthenticationController (Notify.API)
2023-08-10 21:42:10.770 +08:00 [DBG] Executed controller factory for controller Notify.API.Controllers.AuthenticationController (Notify.API)
2023-08-10 21:42:10.780 +08:00 [DBG] Attempting to bind parameter 'request' of type 'Notify.API.Controllers.AuthenticationRequestBody' ...
2023-08-10 21:42:10.784 +08:00 [DBG] Attempting to bind parameter 'request' of type 'Notify.API.Controllers.AuthenticationRequestBody' using the name '' in request data ...
2023-08-10 21:42:10.785 +08:00 [DBG] Selected input formatter 'Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter' for content type 'application/json'.
2023-08-10 21:42:10.804 +08:00 [DBG] Connection id "0HMSPKU9BU9DB", Request id "0HMSPKU9BU9DB:00000002": started reading request body.
2023-08-10 21:42:10.804 +08:00 [DBG] Connection id "0HMSPKU9BU9DB", Request id "0HMSPKU9BU9DB:00000002": done reading request body.
2023-08-10 21:42:10.853 +08:00 [DBG] JSON input formatter succeeded, deserializing to type 'Notify.API.Controllers.AuthenticationRequestBody'
2023-08-10 21:42:10.854 +08:00 [DBG] Done attempting to bind parameter 'request' of type 'Notify.API.Controllers.AuthenticationRequestBody'.
2023-08-10 21:42:10.854 +08:00 [DBG] Done attempting to bind parameter 'request' of type 'Notify.API.Controllers.AuthenticationRequestBody'.
2023-08-10 21:42:10.854 +08:00 [DBG] Attempting to validate the bound parameter 'request' of type 'Notify.API.Controllers.AuthenticationRequestBody' ...
2023-08-10 21:42:10.874 +08:00 [DBG] Done attempting to validate the bound parameter 'request' of type 'Notify.API.Controllers.AuthenticationRequestBody'.
2023-08-10 21:42:11.251 +08:00 [DBG] List of registered output formatters, in the following order: ["Microsoft.AspNetCore.Mvc.Formatters.HttpNoContentOutputFormatter","Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter","Microsoft.AspNetCore.Mvc.Formatters.StreamOutputFormatter","Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter"]
2023-08-10 21:42:11.260 +08:00 [DBG] No information found on request to perform content negotiation.
2023-08-10 21:42:11.260 +08:00 [DBG] Attempting to select an output formatter without using a content type as no explicit content types were specified for the response.
2023-08-10 21:42:11.260 +08:00 [DBG] Attempting to select the first formatter in the output formatters list which can write the result.
2023-08-10 21:42:11.261 +08:00 [DBG] Selected output formatter 'Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter' and content type 'text/plain' to write the response.
2023-08-10 21:42:11.261 +08:00 [INF] Executing OkObjectResult, writing value of type 'System.String'.
2023-08-10 21:42:11.276 +08:00 [INF] Executed action Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API) in 496.4233ms
2023-08-10 21:42:11.278 +08:00 [INF] Executed endpoint 'Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)'
2023-08-10 21:42:11.278 +08:00 [DBG] Connection id "0HMSPKU9BU9DB" completed keep alive response.
2023-08-10 21:42:11.278 +08:00 [INF] Request finished HTTP/1.1 POST https://localhost:7288/api/authentication application/json 99 - 200 - text/plain;+charset=utf-8 721.6096ms

And the logs for the GET:

2023-08-10 21:42:21.897 +08:00 [INF] Request starting HTTP/1.1 GET https://localhost:7288/api/notes/12 - -
2023-08-10 21:42:21.898 +08:00 [DBG] 1 candidate(s) found for the request path '/api/notes/12'
2023-08-10 21:42:21.898 +08:00 [DBG] Endpoint 'Notify.API.Controllers.NotesController.GetNoteById (Notify.API)' with route pattern 'api/notes/{id:int}' is valid for the request path '/api/notes/12'
2023-08-10 21:42:21.898 +08:00 [DBG] Request matched endpoint 'Notify.API.Controllers.NotesController.GetNoteById (Notify.API)'
2023-08-10 21:42:21.898 +08:00 [DBG] Static files was skipped as the request already matched an endpoint.
2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
System.MissingMethodException: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken& signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
2023-08-10 21:42:21.912 +08:00 [INF] Bearer was not authenticated. Failure message: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
2023-08-10 21:42:21.918 +08:00 [INF] Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
2023-08-10 21:42:21.930 +08:00 [INF] AuthenticationScheme: Bearer was challenged.
2023-08-10 21:42:21.930 +08:00 [DBG] Connection id "0HMSPKU9BU9DB" completed keep alive response.
2023-08-10 21:42:21.931 +08:00 [INF] Request finished HTTP/1.1 GET https://localhost:7288/api/notes/12 - - - 401 0 - 33.0822ms
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

1

Thanks to @NeilW to pointing me in the right direction.

The main problem was identified in this log:

2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
System.MissingMethodException: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken& signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()

This failed to authenticate the bearer token:

2023-08-10 21:42:21.912 +08:00 [INF] Bearer was not authenticated. Failure message: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.

Fix:

The Microsoft.IdentityModel.Tokens 6.32.1 contained a transitive package, Microsoft.IdentityModel.Tokens.Jwt6.21.0. I updated the Microsoft.IdentityModel.Tokens.Jwt to 6.32.1 and it solved the issue!

Here are versions of packages and related dependencies:

<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.32.1" />
<PackageReference Include="Microsoft.IdentityModel.Tokens.Jwt" Version="6.32.1" />

Microsoft.IdentityModel.Abstractions 6.32.1
Microsoft.IdentityModel.JsonWebTokens 6.32.1
Microsoft.IdentityModel.Logging 6.32.1
Microsoft.IdentityModel.Protocols 6.21.0
Microsoft.IdentityModel.Protocols.OpenIdConnect 6.21.0
0

Im using a Angular Front End and .Net Core 6.0 API

I had a similar issue, Whenever I added the Authorize Tag to the api endpoint or controller i would sometimes also get a 404 not found error

In my case, I added configurations in the wrong order.

Identity needs to be added before authentication