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

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

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();
}

  1. // validate the credentials
  2. var user = ValidateUser(request.UserName!, request.Password!);
  3. if (user == null)
  4. {
  5. return Unauthorized();
  6. }
  7. /*--- creating a token ---*/
  8. // create security key
  9. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration[&quot;Authentication:SecretForKey&quot;]));
  10. // create signing credentials
  11. var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  12. // create claims for token
  13. var claimsForToken = new List&lt;Claim&gt;
  14. {
  15. new Claim(&quot;sub&quot;, user.UserId.ToString()), //sub is a standardized key for the unique user identifier
  16. new Claim(&quot;given_name&quot;, user.Name),
  17. };
  18. // create token
  19. var jwtSecurityToken = new JwtSecurityToken(
  20. _configuration[&quot;Authentication:Issuer&quot;], // entity that created the token
  21. _configuration[&quot;Authentication:Audience&quot;], // entity for whom the token is intended to be consumed
  22. claimsForToken, // claims containing user info
  23. DateTime.UtcNow, // dateTime that indicates the start of token validity (before this time, the token cannot be used and validation will fail)
  24. DateTime.UtcNow.AddHours(1), // dateTime that indicates the end of token validity (after this time, the token is also invalid and validation will fail)
  25. signingCredentials // with security algorithm
  26. );
  27. // serializers the JWTSecurityToken into a string that is returned
  28. var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
  29. 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:

  1. builder.Services
  2. .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  3. .AddJwtBearer(options =&gt;
  4. {
  5. options.TokenValidationParameters = new()
  6. {
  7. ValidateIssuer = true,
  8. ValidateAudience = true,
  9. ValidateIssuerSigningKey = true,
  10. ValidIssuer = builder.Configuration[&quot;Authentication:Issuer&quot;],
  11. ValidAudience = builder.Configuration[&quot;Authentication:Audience&quot;],
  12. IssuerSigningKey = new SymmetricSecurityKey(
  13. Encoding.UTF8.GetBytes(builder.Configuration[&quot;Authentication:SecretForKey&quot;])
  14. )
  15. };
  16. });

Here is the request pipeline:

  1. app.UseHttpsRedirection();
  2. app.UseAuthentication();
  3. app.UseAuthorization();
  4. app.MapControllers();
  5. 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:

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

I also noticed this logged error in the GET:

  1. 2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
  2. 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;.
  3. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
  4. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; validatedToken)
  5. at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
  6. 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;.
  7. 2023-08-10 21:42:21.918 +08:00 [INF] Authorization failed. These requirements were not met:
  8. DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
  9. 2023-08-10 21:42:21.930 +08:00 [INF] AuthenticationScheme: Bearer was challenged.

Here are the logs for the POST:

  1. 2023-08-10 21:42:10.557 +08:00 [INF] Request starting HTTP/1.1 POST https://localhost:7288/api/authentication application/json 99
  2. 2023-08-10 21:42:10.571 +08:00 [DBG] 1 candidate(s) found for the request path &#39;/api/authentication&#39;
  3. 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;
  4. 2023-08-10 21:42:10.583 +08:00 [DBG] Request matched endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
  5. 2023-08-10 21:42:10.585 +08:00 [DBG] Static files was skipped as the request already matched an endpoint.
  6. 2023-08-10 21:42:10.692 +08:00 [DBG] AuthenticationScheme: Bearer was not authenticated.
  7. 2023-08-10 21:42:10.695 +08:00 [INF] Executing endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
  8. 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).
  9. 2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of authorization
  10. <details>
  11. <summary>英文:</summary>
  12. I&#39;m new to JWT and ASP.NET Core 6 Web API and I&#39;m trying to add authentication to an endpoint.
  13. 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.
  14. `AuthenticationController`:
  15. [HttpPost]
  16. public ActionResult&lt;string&gt; Authenticate([FromBody] AuthenticationRequestBody request)
  17. {
  18. if (!ModelState.IsValid)
  19. {
  20. return Unauthorized();
  21. }
  22. // validate the credentials
  23. var user = ValidateUser(request.UserName!, request.Password!);
  24. if (user == null)
  25. {
  26. return Unauthorized();
  27. }
  28. /*--- creating a token ---*/
  29. // create security key
  30. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration[&quot;Authentication:SecretForKey&quot;]));
  31. // create signing credentials
  32. var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  33. // create claims for token
  34. var claimsForToken = new List&lt;Claim&gt;
  35. {
  36. new Claim(&quot;sub&quot;, user.UserId.ToString()), //sub is a standardized key for the unique user identifier
  37. new Claim(&quot;given_name&quot;, user.Name),
  38. };
  39. // create token
  40. var jwtSecurityToken = new JwtSecurityToken(
  41. _configuration[&quot;Authentication:Issuer&quot;], // entity that created the token
  42. _configuration[&quot;Authentication:Audience&quot;], // entity for whom the token is intended to be consumed
  43. claimsForToken, // claims containing user info
  44. DateTime.UtcNow, // dateTime that indicates the start of token validity (before this time, the token cannot be used and validation will fail)
  45. DateTime.UtcNow.AddHours(1), // dateTime that indicates the end of token validity (after this time, the token is also invalid and validation will fail)
  46. signingCredentials // with security algorithm
  47. );
  48. // serializers the JWTSecurityToken into a string that is returned
  49. var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
  50. return Ok(token);
  51. }
  52. **Note:** `/Authenticate` endpoint is not connected to the database yet and it just calls `ValidateUser()` which returns a constant object just for testing.
  53. Here is my `Program.cs`:
  54. ```csharp
  55. builder.Services
  56. .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  57. .AddJwtBearer(options =&gt;
  58. {
  59. options.TokenValidationParameters = new()
  60. {
  61. ValidateIssuer = true,
  62. ValidateAudience = true,
  63. ValidateIssuerSigningKey = true,
  64. ValidIssuer = builder.Configuration[&quot;Authentication:Issuer&quot;],
  65. ValidAudience = builder.Configuration[&quot;Authentication:Audience&quot;],
  66. IssuerSigningKey = new SymmetricSecurityKey(
  67. Encoding.UTF8.GetBytes(builder.Configuration[&quot;Authentication:SecretForKey&quot;])
  68. )
  69. };
  70. });

Here is the request pipeline:

  1. app.UseHttpsRedirection();
  2. app.UseAuthentication();
  3. app.UseAuthorization();
  4. app.MapControllers();
  5. 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:

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

I also noticed this logged error in the GET:

  1. 2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
  2. 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;.
  3. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
  4. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; validatedToken)
  5. at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
  6. 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;.
  7. 2023-08-10 21:42:21.918 +08:00 [INF] Authorization failed. These requirements were not met:
  8. DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
  9. 2023-08-10 21:42:21.930 +08:00 [INF] AuthenticationScheme: Bearer was challenged.

Here are the logs for the POST:

  1. 2023-08-10 21:42:10.557 +08:00 [INF] Request starting HTTP/1.1 POST https://localhost:7288/api/authentication application/json 99
  2. 2023-08-10 21:42:10.571 +08:00 [DBG] 1 candidate(s) found for the request path &#39;/api/authentication&#39;
  3. 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;
  4. 2023-08-10 21:42:10.583 +08:00 [DBG] Request matched endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
  5. 2023-08-10 21:42:10.585 +08:00 [DBG] Static files was skipped as the request already matched an endpoint.
  6. 2023-08-10 21:42:10.692 +08:00 [DBG] AuthenticationScheme: Bearer was not authenticated.
  7. 2023-08-10 21:42:10.695 +08:00 [INF] Executing endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
  8. 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).
  9. 2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of authorization filters (in the following order): [&quot;None&quot;]
  10. 2023-08-10 21:42:10.767 +08:00 [DBG] Execution plan of resource filters (in the following order): [&quot;None&quot;]
  11. 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;]
  12. 2023-08-10 21:42:10.768 +08:00 [DBG] Execution plan of exception filters (in the following order): [&quot;None&quot;]
  13. 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;]
  14. 2023-08-10 21:42:10.768 +08:00 [DBG] Executing controller factory for controller Notify.API.Controllers.AuthenticationController (Notify.API)
  15. 2023-08-10 21:42:10.770 +08:00 [DBG] Executed controller factory for controller Notify.API.Controllers.AuthenticationController (Notify.API)
  16. 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; ...
  17. 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 ...
  18. 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;.
  19. 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.
  20. 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.
  21. 2023-08-10 21:42:10.853 +08:00 [DBG] JSON input formatter succeeded, deserializing to type &#39;Notify.API.Controllers.AuthenticationRequestBody&#39;
  22. 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;.
  23. 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;.
  24. 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; ...
  25. 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;.
  26. 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;]
  27. 2023-08-10 21:42:11.260 +08:00 [DBG] No information found on request to perform content negotiation.
  28. 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.
  29. 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.
  30. 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.
  31. 2023-08-10 21:42:11.261 +08:00 [INF] Executing OkObjectResult, writing value of type &#39;System.String&#39;.
  32. 2023-08-10 21:42:11.276 +08:00 [INF] Executed action Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API) in 496.4233ms
  33. 2023-08-10 21:42:11.278 +08:00 [INF] Executed endpoint &#39;Notify.API.Controllers.AuthenticationController.Authenticate (Notify.API)&#39;
  34. 2023-08-10 21:42:11.278 +08:00 [DBG] Connection id &quot;0HMSPKU9BU9DB&quot; completed keep alive response.
  35. 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:

  1. 2023-08-10 21:42:21.897 +08:00 [INF] Request starting HTTP/1.1 GET https://localhost:7288/api/notes/12 - -
  2. 2023-08-10 21:42:21.898 +08:00 [DBG] 1 candidate(s) found for the request path &#39;/api/notes/12&#39;
  3. 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;
  4. 2023-08-10 21:42:21.898 +08:00 [DBG] Request matched endpoint &#39;Notify.API.Controllers.NotesController.GetNoteById (Notify.API)&#39;
  5. 2023-08-10 21:42:21.898 +08:00 [DBG] Static files was skipped as the request already matched an endpoint.
  6. 2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
  7. 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;.
  8. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
  9. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; validatedToken)
  10. at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
  11. 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;.
  12. 2023-08-10 21:42:21.918 +08:00 [INF] Authorization failed. These requirements were not met:
  13. DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
  14. 2023-08-10 21:42:21.930 +08:00 [INF] AuthenticationScheme: Bearer was challenged.
  15. 2023-08-10 21:42:21.930 +08:00 [DBG] Connection id &quot;0HMSPKU9BU9DB&quot; completed keep alive response.
  16. 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指导我走向了正确的方向。

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

  1. 2023-08-10 21:42:21.910 +08:00 [INF] 未能验证令牌。
  2. System.MissingMethodException: 未找到方法:'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'
  3. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
  4. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; validatedToken)
  5. at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()

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

  1. 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,问题得以解决!

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

  1. &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.21&quot; /&gt;
  2. &lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens&quot; Version=&quot;6.32.1&quot; /&gt;
  3. &lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens.Jwt&quot; Version=&quot;6.32.1&quot; /&gt;
  4. Microsoft.IdentityModel.Abstractions 6.32.1
  5. Microsoft.IdentityModel.JsonWebTokens 6.32.1
  6. Microsoft.IdentityModel.Logging 6.32.1
  7. Microsoft.IdentityModel.Protocols 6.21.0
  8. 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:

  1. 2023-08-10 21:42:21.910 +08:00 [INF] Failed to validate the token.
  2. 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;.
  3. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken&amp; signatureValidatedToken)
  4. at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&amp; validatedToken)
  5. at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()

This failed to authenticate the bearer token:

  1. 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:

  1. &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.21&quot; /&gt;
  2. &lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens&quot; Version=&quot;6.32.1&quot; /&gt;
  3. &lt;PackageReference Include=&quot;Microsoft.IdentityModel.Tokens.Jwt&quot; Version=&quot;6.32.1&quot; /&gt;
  4. Microsoft.IdentityModel.Abstractions 6.32.1
  5. Microsoft.IdentityModel.JsonWebTokens 6.32.1
  6. Microsoft.IdentityModel.Logging 6.32.1
  7. Microsoft.IdentityModel.Protocols 6.21.0
  8. 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:

确定