.Net Core API JWT 令牌验证

Lok*_*Dil 6 c# jwt bearer-token .net-core

在 .Net Core WEB API 中实现了 JWT Bearer Token 验证,如下所述:

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(opt =>
                {
                    opt.Audience = Configuration["AAD:ResourceId"];
                    opt.Authority = $"{Configuration["AAD:Instance"]}{Configuration["AAD:TenantId"]}";
                });
Run Code Online (Sandbox Code Playgroud)

怀疑上面提到的代码只会验证受众和权威吗?或者它将验证所有参数,例如过期和签名等?

我们是否需要显式验证签名以检查有效负载是否被篡改?

Pab*_*lde 10

我想你正在寻找这个:

\n

https://zhiliaxu.github.io/how-do-aspnet-core-services-validate-jwt-signature-signed-by-aad.html

\n

这里zhiliaxu详细解释了使用时如何以及实际验证了什么.AddJwtBearer(),他们的结论是:

\n
\n

现在很清楚

\n
    \n
  • JWT 签名经过验证,无需在我们的服务\xe2\x80\x99s 源代码中提供任何密钥或认证。
  • \n
  • JWT 签名密钥是根据\nJwtBearerOptions.Authority 属性从众所周知的 URL https://login.microsoftonline.com/common/discovery/keys检索的。
  • \n
  • 签名密钥缓存在 JwtBearerHandler 单例实例中,因此我们的 ASP.NET Core 服务只需在其整个生命周期中检索它\nonce。
  • \n
\n
\n

另外根据这篇文章我们可以看看ValidateToken()MSDN上的文档:https://learn.microsoft.com/en-us/dotnet/api/system.identitymodel.tokens.jwt.jwtsecuritytokenhandler.validatetoken ?view=azure- dotnet您可以在其中找到该方法抛出的不同异常:

\n
    \n
  • SecurityTokenDecryptionFailedException:令牌是 JWE 无法解密。
  • \n
  • SecurityTokenEncryptionKeyNotFoundException:令牌“kid”标头声明不为空且解密失败。
  • \n
  • SecurityTokenException:令牌“enc”标头声明为 null 或为空。
  • \n
  • SecurityTokenExpiredException:令牌“exp”声明为 < DateTime.UtcNow。
  • \n
  • SecurityTokenInvalidAudienceException:令牌“aud”声明与 ValidAudience 或 ValidAudience 之一不匹配。
  • \n
  • SecurityTokenInvalidLifetimeException:令牌“nbf”声明>“exp”声明。
  • \n
  • SecurityTokenInvalidSignatureException:token.signature 格式不正确。
  • \n
  • SecurityTokenNoExpirationException:TokenReplayCache 不为 null,并且expirationTime.HasValue 为 false。设置 TokenReplayCache 后,令牌需要过期时间。
  • \n
  • SecurityTokenNotYetValidException:令牌“nbf”声明为 > DateTime.UtcNow。
  • \n
  • SecurityTokenReplayAddFailedException:无法将令牌添加到 TokenReplayCache。
  • \n
  • SecurityTokenReplayDetectedException:在缓存中找到令牌。
  • \n
\n