在 Asp.Net Core Web Api 中验证 B2C JWT 令牌

Validating B2C JWT tokens in Asp.Net Core Web Api

我正在使用 B2C 来保护 Asp.Net Core 中的 WebApi。我的代码如下。我需要验证令牌还是中间件为我做的?我想如果每个人都必须这样做,我会更容易找到一些示例代码,但我似乎无法在这方面得到任何真正的指导。

然而,这个 B2C documentation 声明我的 api 进行了验证。

我发现了一个 sample but it's not for Core and they're using CertificateValidator = X509CertificateValidator.None. Doesn't that defeat the purpose? And another sample here 他们 正在 做这件事。

我不需要 B2C 的签名密钥等等吗?

我可以从中拼凑出一个解决方案,但我真的需要这样做吗?

提前致谢。

        app.UseJwtBearerAuthentication(new JwtBearerOptions()
        {
            AuthenticationScheme = Constants.B2CAuthenticationSchemeName,
            AutomaticAuthenticate = false,
            MetadataAddress = string.Format(
                _identityConfig.B2CInfo.AadInstance,
                _identityConfig.B2CInfo.Tenant,
                _identityConfig.B2CInfo.Policies
                    .Where(p => p.IsDefaultSignUpSignInPolicy == true)
                    .First()
                    .Name),
            Audience = _identityConfig.B2CInfo.ClientId,
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidateLifetime = true,
                RequireExpirationTime = true,
                RequireSignedTokens = true,
            },
            Events = new JwtBearerEvents
            {
                OnAuthenticationFailed = B2CAuthenticationFailed
            }
        });

Do I need to validate the tokens or is the middleware doing it for me?

JWT bearer middleware 会为你做这件事(默认情况下,它会自动拒绝未签名或伪造的令牌,所以你不需要明确地将 RequireSignedTokens 设置为 true)。

Doesn't that defeat the purpose?

使用证书中嵌入的 public 非对称密钥(例如 RSA 或 ECDSA)验证签名与验证证书本身(特别是其链)之间存在差异。 ASP.NET Core 完全支持签名验证,但尚不支持证书验证。

Don't I have to have the signing key from B2C and all that?

JWT 承载中间件会自动从 B2C 的发现端点检索它,因此无需手动执行此操作。如需更多信息,请随时阅读 OIDC 发现规范:https://openid.net/specs/openid-connect-discovery-1_0.html