Manual decode a Bearer Token using Azure Active Directory, How do I validate?

此生再无相见时 提交于 2021-01-29 13:00:52

问题


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

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}");

回答1:


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

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 

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 .

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 .



来源:https://stackoverflow.com/questions/57830076/manual-decode-a-bearer-token-using-azure-active-directory-how-do-i-validate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!