51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

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

英文:

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

问题 {#heading}

以下是您要翻译的内容:

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

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

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

        // create token
        var jwtSecurityToken = new JwtSecurityToken(
                _configuration[&amp;quot;Authentication:Issuer&amp;quot;],    // entity that created the token
                _configuration[&amp;quot;Authentication:Audience&amp;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 =&amp;gt;
    {
        options.TokenValidationParameters = new()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration[&amp;quot;Authentication:Issuer&amp;quot;],
            ValidAudience = builder.Configuration[&amp;quot;Authentication:Audience&amp;quot;],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration[&amp;quot;Authentication:SecretForKey&amp;quot;])
            )
        };
    });
</code></pre>
 <p>Here is the request pipeline:</p>
 <pre tabindex="0" style="color:#f8f8f2;background-color:#272822;"><code><span style="display:flex;"><span>app.UseHttpsRedirection();
</span></span><span style="display:flex;"><span>app.UseAuthentication();
</span></span><span style="display:flex;"><span>app.UseAuthorization();
</span></span><span style="display:flex;"><span>app.MapControllers();
</span></span><span style="display:flex;"><span>app.Run();
</span></span></code></pre>
 <p><strong>Note</strong> that the <code>Authentication</code> configuration is in my <code>secrets.json</code></p>
 <hr>
 <p>Upon testing the <code>/Authenticate</code> endpoint using Postman and attaching the Authorization header with the <code>Bearer {token}</code> format, and subsequently calling an action with the <code>[Authorize]</code> attribute, I consistently get a <code>401 Not Authorized</code> response. The <code>WWW-Authenticate</code> header indicates an error of <code>Bearer error=&amp;quot;invalid token&amp;quot;</code>.</p>
 <p>When I make the POST request, I get this log:</p>
 <pre><code>2023-08-10 21:42:10.692 +08:00 [DBG] AuthenticationScheme: Bearer was not authenticated.
</code></pre>
 <p>I also noticed this logged error in the GET:</p>
 <pre><code>2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
System.MissingMethodException: Method not found: &amp;#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&amp;#39;.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp;amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp;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: &amp;#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&amp;#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.
</code></pre>
 <p>Here are the logs for the <code>POST</code>:</p>
 <pre><code>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 &amp;#39;/api/authentication&amp;#39;
2023-08-10 21:42:10.583 +08:00 [DBG] Endpoint &amp;#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&amp;#39; with route pattern &amp;#39;api/authentication&amp;#39; is valid for the request path &amp;#39;/api/authentication&amp;#39;
2023-08-10 21:42:10.583 +08:00 [DBG] Request matched endpoint &amp;#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&amp;#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 &amp;#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&amp;#39;
2023-08-10 21:42:10.765 +08:00 [INF] Route matched with {action = &amp;quot;Authenticate&amp;quot;, controller = &amp;quot;Authentication&amp;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): [&amp;quot;None&amp;quot;]
2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of resource filters (in the following order): [&amp;quot;None&amp;quot;]
2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of action filters (in the following order): [&amp;quot;Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter (Order: -3000)&amp;quot;,&amp;quot;Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter (Order: -2000)&amp;quot;]
2023-08-10 21:42:10.768 +08:00 [DBG] Execution plan of exception filters (in the following order): [&amp;quot;None&amp;quot;]
2023-08-10 21:42:10.768 +08:00 [DBG] Execution plan of result filters (in the following order): [&amp;quot;Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter (Order: -2000)&amp;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 &amp;#39;request&amp;#39; of type &amp;#39;Notify.API.Controllers.AuthenticationRequestBody&amp;#39; ...
2023-08-10 21:42:10.784 +08:00 [DBG] Attempting to bind parameter &amp;#39;request&amp;#39; of type &amp;#39;Notify.API.Controllers.AuthenticationRequestBody&amp;#39; using the name &amp;#39;&amp;#39; in request data ...
2023-08-10 21:42:10.785 +08:00 [DBG] Selected input formatter &amp;#39;Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter&amp;#39; for content type &amp;#39;application/json&amp;#39;.
2023-08-10 21:42:10.804 +08:00 [DBG] Connection id &amp;quot;0HMSPKU9BU9DB&amp;quot;, Request id &amp;quot;0HMSPKU9BU9DB:00000002&amp;quot;: started reading request body.
2023-08-10 21:42:10.804 +08:00 [DBG] Connection id &amp;quot;0HMSPKU9BU9DB&amp;quot;, Request id &amp;quot;0HMSPKU9BU9DB:00000002&amp;quot;: done reading request body.
2023-08-10 21:42:10.853 +08:00 [DBG] JSON input formatter succeeded, deserializing to type &amp;#39;Notify.API.Controllers.AuthenticationRequestBody&amp;#39;
2023-08-10 21:42:10.854 +08:00 [DBG] Done attempting to bind parameter &amp;#39;request&amp;#39; of type &amp;#39;Notify.API.Controllers.AuthenticationRequestBody&amp;#39;.
2023-08-10 21:42:10.854 +08:00 [DBG] Done attempting to bind parameter &amp;#39;request&amp;#39; of type &amp;#39;Notify.API.Controllers.AuthenticationRequestBody&amp;#39;.
2023-08-10 21:42:10.854 +08:00 [DBG] Attempting to validate the bound parameter &amp;#39;request&amp;#39; of type &amp;#39;Notify.API.Controllers.AuthenticationRequestBody&amp;#39; ...
2023-08-10 21:42:10.874 +08:00 [DBG] Done attempting to validate the bound parameter &amp;#39;request&amp;#39; of type &amp;#39;Notify.API.Controllers.AuthenticationRequestBody&amp;#39;.
2023-08-10 21:42:11.251 +08:00 [DBG] List of registered output formatters, in the following order: [&amp;quot;Microsoft.AspNetCore.Mvc.Formatters.HttpNoContentOutputFormatter&amp;quot;,&amp;quot;Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter&amp;quot;,&amp;quot;Microsoft.AspNetCore.Mvc.Formatters.StreamOutputFormatter&amp;quot;,&amp;quot;Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter&amp;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 &amp;#39;Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter&amp;#39; and content type &amp;#39;text/plain&amp;#39; to write the response.
2023-08-10 21:42:11.261 +08:00 [INF] Executing OkObjectResult, writing value of type &amp;#39;System.String&amp;#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 &amp;#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&amp;#39;
2023-08-10 21:42:11.278 +08:00 [DBG] Connection id &amp;quot;0HMSPKU9BU9DB&amp;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
</code></pre>
 <p>And the logs for the <code>GET</code>:</p>
 <pre><code>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 &amp;#39;/api/notes/12&amp;#39;
2023-08-10 21:42:21.898 +08:00 [DBG] Endpoint &amp;#39;Notify.API.Controllers.NotesController.GetNoteById (Notify.API)&amp;#39; with route pattern &amp;#39;api/notes/{id:int}&amp;#39; is valid for the request path &amp;#39;/api/notes/12&amp;#39;
2023-08-10 21:42:21.898 +08:00 [DBG] Request matched endpoint &amp;#39;Notify.API.Controllers.NotesController.GetNoteById (Notify.API)&amp;#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: &amp;#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&amp;#39;.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp;amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp;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: &amp;#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&amp;#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 &amp;quot;0HMSPKU9BU9DB&amp;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
</code></pre>
 <h1 id="1">答案1</h1>
 <p><strong>得分</strong>: 1</p>
 <p>感谢@NeilW指导我走向了正确的方向。</p>
 <p>主要问题在这个日志中被识别出来了:</p>
 <pre tabindex="0" style="color:#f8f8f2;background-color:#272822;"><code><span style="display:flex;"><span>2023-08-10 21:42:21.910 +08:00 [INF] 未能验证令牌。
</span></span><span style="display:flex;"><span>System.MissingMethodException: 未找到方法:'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'。
</span></span><span style="display:flex;"><span>   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp;amp; signatureValidatedToken)
</span></span><span style="display:flex;"><span>   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp;amp; validatedToken)
</span></span><span style="display:flex;"><span>   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
</span></span></code></pre>
 <p>这导致了无法验证承载令牌的问题:</p>
 <pre tabindex="0" style="color:#f8f8f2;background-color:#272822;"><code><span style="display:flex;"><span>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)'。
</span></span></code></pre>
 <p><strong>修复:</strong></p>
 <p><code>Microsoft.IdentityModel.Tokens 6.32.1</code> 包含了一个传递性包,<code>Microsoft.IdentityModel.Tokens.Jwt</code><em><code>6.21.0</code></em>。<strong>我将 <code>Microsoft.IdentityModel.Tokens.Jwt</code> 更新到了 <code>6.32.1</code>,问题得以解决!</strong></p>
 <p>以下是包及其相关依赖项的版本:</p>
 <pre tabindex="0" style="color:#f8f8f2;background-color:#272822;"><code><span style="display:flex;"><span>&amp;lt;PackageReference Include=&amp;quot;Microsoft.AspNetCore.Authentication.JwtBearer&amp;quot; Version=&amp;quot;6.0.21&amp;quot; /&amp;gt;
</span></span><span style="display:flex;"><span>&amp;lt;PackageReference Include=&amp;quot;Microsoft.IdentityModel.Tokens&amp;quot; Version=&amp;quot;6.32.1&amp;quot; /&amp;gt;
</span></span><span style="display:flex;"><span>&amp;lt;PackageReference Include=&amp;quot;Microsoft.IdentityModel.Tokens.Jwt&amp;quot; Version=&amp;quot;6.32.1&amp;quot; /&amp;gt;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Abstractions 6.32.1
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.JsonWebTokens 6.32.1
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Logging 6.32.1
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Protocols 6.21.0
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Protocols.OpenIdConnect 6.21.0
</span></span></code></pre>
 <details>
  <summary>英文:</summary>
  <p>Thanks to @NeilW to pointing me in the right direction.</p>
  <p>The main problem was identified in this log:</p>
  <pre><code>2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
System.MissingMethodException: Method not found: &amp;#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&amp;#39;.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp;amp; signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp;amp; validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
</code></pre>
  <p>This failed to authenticate the bearer token:</p>
  <pre><code>2023-08-10 21:42:21.912 +08:00 [INF] Bearer was not authenticated. Failure message: Method not found: &amp;#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&amp;#39;.
</code></pre>
  <hr>
  <p><strong>Fix:</strong></p>
  <p>The <code>Microsoft.IdentityModel.Tokens 6.32.1</code> contained a transitive package, <code>Microsoft.IdentityModel.Tokens.Jwt</code><em><code>6.21.0</code></em>. <strong>I updated the <code>Microsoft.IdentityModel.Tokens.Jwt</code> to <code>6.32.1</code> and it solved the issue!</strong></p>
  <p>Here are versions of packages and related dependencies:</p>
  <pre tabindex="0" style="color:#f8f8f2;background-color:#272822;"><code><span style="display:flex;"><span>&amp;lt;PackageReference Include=&amp;quot;Microsoft.AspNetCore.Authentication.JwtBearer&amp;quot; Version=&amp;quot;6.0.21&amp;quot; /&amp;gt;
</span></span><span style="display:flex;"><span>&amp;lt;PackageReference Include=&amp;quot;Microsoft.IdentityModel.Tokens&amp;quot; Version=&amp;quot;6.32.1&amp;quot; /&amp;gt;
</span></span><span style="display:flex;"><span>&amp;lt;PackageReference Include=&amp;quot;Microsoft.IdentityModel.Tokens.Jwt&amp;quot; Version=&amp;quot;6.32.1&amp;quot; /&amp;gt;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Abstractions 6.32.1
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.JsonWebTokens 6.32.1
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Logging 6.32.1
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Protocols 6.21.0
</span></span><span style="display:flex;"><span>Microsoft.IdentityModel.Protocols.OpenIdConnect 6.21.0
</span></span></code></pre>
 </details>
 <h1 id="2">答案2</h1>
 <p><strong>得分</strong>: 0</p>
 <p>我正在使用Angular前端和.Net Core 6.0 API。</p>
 <p>我遇到了类似的问题,每当我向API端点或控制器添加Authorize标签时,有时也会收到404未找到错误。</p>
 <p>在我的情况下,我以错误的顺序添加了配置。</p>
 <p>在进行身份验证之前需要添加身份验证。</p>
 <details>
  <summary>英文:</summary>
  <p>Im using a Angular Front End and .Net Core 6.0 API</p>
  <p>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</p>
  <p>In my case, I added configurations in the wrong order.</p>
  <p>Identity needs to be added before authentication</p>
 </details>
 <p></p>
</div>

```
赞(1)
未经允许不得转载:工具盒子 » JWT Authentication Issue in ASP.NET Core 6 Web API: getting 401 unauthorized despite proper bearer token setup