使用 Azure Active Directory 手动解码不记名令牌,如何验证? [英] Manual decode a Bearer Token using Azure Active Directory, How do I validate?

查看:27
本文介绍了使用 Azure Active Directory 手动解码不记名令牌,如何验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Net Core WebApi 应用程序中使用下面的代码,并且运行良好.

I'm using the code below in a Net Core WebApi app and it's working well.

我可以解码它生成的 JWT,但我还想验证它的签名.但是,我从哪里获得验证它的密钥?

I can decode the JWT that it produces, but I would also like to verify it's signature. But, where do I get the key to verify it with?

            tenant = Configuration.GetSection("AzureAD:Tenant").Value;
            Logger.AppLogDebug("tenat value found: [{0}]", tenant);

            azureAdInstance = Configuration.GetSection("AzureAD:AzureADInstance").Value;
            Logger.AppLogDebug("azureAdInstance value found: [{0}]", azureAdInstance);

            audience = Configuration.GetSection("AzureAD:Audience").Value;
            Logger.AppLogDebug("Audience value found: [{0}]", audience);

        var authority = $"{azureAdInstance}{tenant}";
        Logger.AppLogDebug("authority value set to: [{0}]", authority);

        var authContext = new AuthenticationContext(authority);

        var clientCredential = new ClientCredential(key, secret);

            var token = authContext.AcquireTokenAsync(audience, clientCredential).Result.AccessToken;
            return new ObjectResult($"Bearer {token}");

推荐答案

您可以使用 JwtBearerAddAzureADBearer 中间件来验证访问令牌.以便在收到客户端请求时,您的 web api 将自动解码令牌并验证签名.您可以参考以下链接了解如何使用这两个中间件:

You can use JwtBearer or AddAzureADBearer middleware to validate the access token . So that when receiving request form client , your web api will automatically decode token and verify the signature . You can refer to below link for how to use the two middlewares :

https://stackoverflow.com/a/57619013/5751404

如果您想手动验证 jwt 令牌,在验证访问令牌的签名时,您应该获取公钥,因为 Azure AD 可能会使用一组特定的公钥-私钥对中的任何一个对令牌进行签名,密钥可以可在以下位置找到:

If you want to manually verify the jwt token , When validating the signature of access token , you should get the public key since Azure AD may sign token using any one of a certain set of public-private key pairs , the keys could be found at :

https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration 

在 JSON 响应中,您将看到一个属性 jwks_uri,它是包含 Azure AD 的 JSON Web 密钥集的 URI.匹配 jwt token 中的 Kid 声明,您可以找到 AAD 使用非对称加密算法对令牌进行签名的密钥,例如 RSA 256 默认情况下.

Within the JSON response, you’ll see a property jwks_uri which is the URI that contains the JSON Web Key Set for Azure AD. Matching the kid claim in jwt token , you can find the key which AAD used to sign the token with asymmetric encryption algorithms, such as RSA 256 by default .

然后您可以使用以下命令验证令牌:

Then you can validate the token with :

public JwtSecurityToken validate(string token,string key){

    var rsa = new RSACryptoServiceProvider();
    string exponentvalue = "AQAB";
    var e = Base64UrlEncoder.DecodeBytes(exponentvalue);
    var N = key;
    var modulus = Base64UrlEncoder.DecodeBytes(N);
    rsa.ImportParameters(
        new RSAParameters()
        {
            Modulus = modulus,
            Exponent = e
        });
    var signingKey = new RsaSecurityKey(rsa);

    TokenValidationParameters validationParameters = new TokenValidationParameters
    {
        ValidateAudience = false,
        ValidateIssuer = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = signingKey,
        ValidateLifetime = false
    };

    JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();

    SecurityToken jwt;

    var result = tokendHandler.ValidateToken(token, validationParameters, out jwt);

    return jwt as JwtSecurityToken;
}

我还没有测试过上面的代码,但你可以尝试从它开始.

I haven't test above codes but you can try and start with that .

此外,您正在使用客户端凭据流获取特定资源的令牌.如果资源是 Microsoft 托管的 api,例如 Microsoft Graph APIAzure Management API 等.您不需要验证访问您的应用程序中的令牌.将带有令牌的请求发送到 Microsoft 托管的 apis 时,它将为您验证令牌.

In addition , you are using client credential flow to acquiring token for specific resource . If the resource is the Microsoft hosted apis such as Microsoft Graph API, Azure Management API etc.. You don't need to validate the access token in your application . When sending request with token to Microsoft hosted apis , it will validate the tokens for you .

这篇关于使用 Azure Active Directory 手动解码不记名令牌,如何验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆