英文:
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\[\"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
\<details\>
\<summary\>英文:\</summary\>
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&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;])
)
};
});
</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=&quot;invalid token&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: &#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.
</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 &#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
</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 &#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
</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; signatureValidatedToken)
</span></span><span style="display:flex;"><span> at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&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>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.21&quot; /&gt;
</span></span><span style="display:flex;"><span>&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens&quot; Version=&quot;6.32.1&quot; /&gt;
</span></span><span style="display:flex;"><span>&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens.Jwt&quot; Version=&quot;6.32.1&quot; /&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: &#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()
</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: &#39;Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)&#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>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.21&quot; /&gt;
</span></span><span style="display:flex;"><span>&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens&quot; Version=&quot;6.32.1&quot; /&gt;
</span></span><span style="display:flex;"><span>&lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens.Jwt&quot; Version=&quot;6.32.1&quot; /&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>
```