JWT Authentication Issue in ASP.NET Core 6 Web API: getting 401 unauthorized despite proper bearer token setup

huangapple go评论90阅读模式
英文:

JWT Authentication Issue in ASP.NET Core 6 Web API: getting 401 unauthorized despite proper bearer token setup

问题

以下是您要翻译的内容:

"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[&quot;Authentication:SecretForKey&quot;]));

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

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

// create token
var jwtSecurityToken = new JwtSecurityToken(
        _configuration[&quot;Authentication:Issuer&quot;],    // entity that created the token
        _configuration[&quot;Authentication:Audience&quot;],  // 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 =&gt;
    {
        options.TokenValidationParameters = new()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration[&quot;Authentication:Issuer&quot;],
            ValidAudience = builder.Configuration[&quot;Authentication:Audience&quot;],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration[&quot;Authentication:SecretForKey&quot;])
            )
        };
    });

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=&quot;invalid token&quot;.

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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; 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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.
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 &#39;/api/authentication&#39;
2023-08-10 21:42:10.583 +08:00 [DBG] Endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39; with route pattern &#39;api/authentication&#39; is valid for the request path &#39;/api/authentication&#39;
2023-08-10 21:42:10.583 +08:00 [DBG] Request matched endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
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 &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
2023-08-10 21:42:10.765 +08:00 [INF] Route matched with {action = &quot;Authenticate&quot;, controller = &quot;Authentication&quot;}. 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

<details>
<summary>英文:</summary>

I&#39;m new to JWT and ASP.NET Core 6 Web API and I&#39;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&lt;string&gt; 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[&quot;Authentication:SecretForKey&quot;]));

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

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

        // create token
        var jwtSecurityToken = new JwtSecurityToken(
                _configuration[&quot;Authentication:Issuer&quot;],    // entity that created the token
                _configuration[&quot;Authentication:Audience&quot;],  // 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`:

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

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=&quot;invalid token&quot;.

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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; 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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.
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 &#39;/api/authentication&#39;
2023-08-10 21:42:10.583 +08:00 [DBG] Endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39; with route pattern &#39;api/authentication&#39; is valid for the request path &#39;/api/authentication&#39;
2023-08-10 21:42:10.583 +08:00 [DBG] Request matched endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
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 &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
2023-08-10 21:42:10.765 +08:00 [INF] Route matched with {action = &quot;Authenticate&quot;, controller = &quot;Authentication&quot;}. 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): [&quot;None&quot;]
2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of resource filters (in the following order): [&quot;None&quot;]
2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of action filters (in the following order): [&quot;Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter (Order: -3000)&quot;,&quot;Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter (Order: -2000)&quot;]
2023-08-10 21:42:10.768 +08:00 [DBG] Execution plan of exception filters (in the following order): [&quot;None&quot;]
2023-08-10 21:42:10.768 +08:00 [DBG] Execution plan of result filters (in the following order): [&quot;Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter (Order: -2000)&quot;]
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 &#39;request&#39; of type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39; ...
2023-08-10 21:42:10.784 +08:00 [DBG] Attempting to bind parameter &#39;request&#39; of type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39; using the name &#39;&#39; in request data ...
2023-08-10 21:42:10.785 +08:00 [DBG] Selected input formatter &#39;Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter&#39; for content type &#39;application/json&#39;.
2023-08-10 21:42:10.804 +08:00 [DBG] Connection id &quot;0HMSPKU9BU9DB&quot;, Request id &quot;0HMSPKU9BU9DB:00000002&quot;: started reading request body.
2023-08-10 21:42:10.804 +08:00 [DBG] Connection id &quot;0HMSPKU9BU9DB&quot;, Request id &quot;0HMSPKU9BU9DB:00000002&quot;: done reading request body.
2023-08-10 21:42:10.853 +08:00 [DBG] JSON input formatter succeeded, deserializing to type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39;
2023-08-10 21:42:10.854 +08:00 [DBG] Done attempting to bind parameter &#39;request&#39; of type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39;.
2023-08-10 21:42:10.854 +08:00 [DBG] Done attempting to bind parameter &#39;request&#39; of type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39;.
2023-08-10 21:42:10.854 +08:00 [DBG] Attempting to validate the bound parameter &#39;request&#39; of type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39; ...
2023-08-10 21:42:10.874 +08:00 [DBG] Done attempting to validate the bound parameter &#39;request&#39; of type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39;.
2023-08-10 21:42:11.251 +08:00 [DBG] List of registered output formatters, in the following order: [&quot;Microsoft.AspNetCore.Mvc.Formatters.HttpNoContentOutputFormatter&quot;,&quot;Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter&quot;,&quot;Microsoft.AspNetCore.Mvc.Formatters.StreamOutputFormatter&quot;,&quot;Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter&quot;]
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 &#39;Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter&#39; and content type &#39;text/plain&#39; to write the response.
2023-08-10 21:42:11.261 +08:00 [INF] Executing OkObjectResult, writing value of type &#39;System.String&#39;.
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 &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
2023-08-10 21:42:11.278 +08:00 [DBG] Connection id &quot;0HMSPKU9BU9DB&quot; 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 &#39;/api/notes/12&#39;
2023-08-10 21:42:21.898 +08:00 [DBG] Endpoint &#39;Notify.API.Controllers.NotesController.GetNoteById (Notify.API)&#39; with route pattern &#39;api/notes/{id:int}&#39; is valid for the request path &#39;/api/notes/12&#39;
2023-08-10 21:42:21.898 +08:00 [DBG] Request matched endpoint &#39;Notify.API.Controllers.NotesController.GetNoteById (Notify.API)&#39;
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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; 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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.
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 &quot;0HMSPKU9BU9DB&quot; 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

答案1

得分: 1

感谢@NeilW指导我走向了正确的方向。

主要问题在这个日志中被识别出来了:

2023-08-10 21:42:21.910 +08:00 [INF] 未能验证令牌。
System.MissingMethodException: 未找到方法:'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&amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()

这导致了无法验证承载令牌的问题:

2023-08-10 21:42:21.912 +08:00 [INF] 承载令牌未经验证。失败消息:未找到方法:'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'。

修复:

Microsoft.IdentityModel.Tokens 6.32.1 包含了一个传递性包,Microsoft.IdentityModel.Tokens.Jwt6.21.0我将 Microsoft.IdentityModel.Tokens.Jwt 更新到了 6.32.1,问题得以解决!

以下是包及其相关依赖项的版本:

&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.21&quot; /&gt;
&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens&quot; Version=&quot;6.32.1&quot; /&gt;
&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens.Jwt&quot; Version=&quot;6.32.1&quot; /&gt;

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
英文:

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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; 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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#39;.

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:

&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.21&quot; /&gt;
&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens&quot; Version=&quot;6.32.1&quot; /&gt;
&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens.Jwt&quot; Version=&quot;6.32.1&quot; /&gt;

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

答案2

得分: 0

我正在使用Angular前端和.Net Core 6.0 API。

我遇到了类似的问题,每当我向API端点或控制器添加Authorize标签时,有时也会收到404未找到错误。

在我的情况下,我以错误的顺序添加了配置。

在进行身份验证之前需要添加身份验证。

英文:

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

huangapple
  • 本文由 发表于 2023年8月10日 21:55:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定