asp.net-core - 在 Asp.Net Core Web Api 中验证 B2C JWT token

标签 asp.net-core azure-ad-b2c

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

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

我找到了 sample但它不适用于 Core,他们正在使用 CertificateValidator = X509CertificateValidator.None .这不是违背目的吗?还有一个 sample here他们在哪里正在做。

我不需要从 B2C 获得签名 key 吗?

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

提前致谢。

        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 不记名中间件会为您执行此操作(默认情况下,它会自动拒绝未签名或伪造的 token ,因此您无需将 RequireSignedTokens 显式设置为 true )。

Doesn't that defeat the purpose?



使用嵌入在证书中的公共(public)非对称 key (例如 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

关于asp.net-core - 在 Asp.Net Core Web Api 中验证 B2C JWT token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417803/

相关文章:

c# - 与.net core和身份框架的集成测试

asp.net-core - 使用 Microsoft.DotNet.Web.Spa.ProjectTemplates::2.0.0 时, `dotnet run` 与 `npm start` 没有什么不同吗?

c# - 如何将数据(数组)添加到 Identityserver 4 生成的 jwt token

Azure AD B2C : AcquireTokenSilentAsync returns empty access token

azure - 配置 Azure B2C AD 以使用身份验证器应用

azure - AzureAD 应用程序如何撤销自己的同意? (删除委托(delegate)或应用程序权限)

c# - Razor @Json.Serialize 对各个属性的处理在 ASP.NET Core 中不一致

asp.net-core - Kestrel/IIS Express 需要重新启动才能在浏览器中显示编辑的 .cshtml View 更改

Azure AD B2C - 我们可以限制 adb2c 中用户的并发登录吗?

oauth-2.0 - B2C返回的 token 不被JWT.MS解码