使用来自“jwks_uri”端点的值验证从 azure ad b2c 收到的令牌

Shu*_*ari 1 rsa azure jwt azure-active-directory azure-ad-b2c

我从公用事业服务获取 azure 广告访问令牌,我想使用一些标准令牌验证参数来验证它,其中包括发行者、受众和发行者签名密钥。现在我有发行者和受众,但我没有发行者签名钥匙。

但是我已经使用 azure ad b2c 的 jwks_uri 端点提取了关键信息,它给了我一个 json 输出

{
  "keys": [
    {
      "kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4......",
      "nbf": 1493763266,
      "use": "sig",
      "kty": "RSA",
      "e": "AQAB",
      "n": "tVKUtcx_n9rt5afY_2WFNvU6PlFMggCatsZ3l4RjKxH0jgdLq6CScb0P3ZGXYbPzXvmmL...."
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我尝试仅使用 n 值作为键,但出现令牌验证失败的异常。现在我想知道如何获取发行者签名密钥来验证令牌。n+e (string concatenation ?) 是一个解决方案吗?我看到了一个类似的问题Azure AD B2C - 令牌验证不起作用,但它没有回答我的问题,因此想知道在 .net core 中执行它的确切方法。

Jim*_* Xu 8

根据我的理解,您要验证访问令牌。如果是这样,我们可以使用sdkSystem.IdentityModel.Tokens来实现它。例如

 var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
                                   "https://testb2ctenant05.b2clogin.com/testB2CTenant05.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_test",
                                    new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever());
            CancellationToken ct = default(CancellationToken);
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            var discoveryDocument = await configurationManager.GetConfigurationAsync(ct);
            var signingKeys = discoveryDocument.SigningKeys;
            var validationParameters = new TokenValidationParameters
            {
                RequireExpirationTime = true,
                RequireSignedTokens = true,
                ValidateIssuer = true,
                ValidIssuer = discoveryDocument.Issuer,
                ValidateIssuerSigningKey = true,
                IssuerSigningKeys = signingKeys,
                ValidateLifetime = true,

            };

 var principal = new JwtSecurityTokenHandler()
            .ValidateToken(token, validationParameters, out var rawValidatedToken);
Run Code Online (Sandbox Code Playgroud)