1

i want to us Key Vault key to create JWT token and then validate it.

Im using this code:

public static async Task<string> SignJwt()
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authentication"));
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[] { new Claim("id", "1") }),
        Expires = DateTime.UtcNow.AddDays(7),
        SigningCredentials = new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);
}

and it works fine. I was googling a lot and found this snippet for SigningCredentials using Identity extension nuget:

new SigningCredentials(new KeyVaultSecurityKey("https://myvault.vault.azure.net/keys/mykey/keyid", new KeyVaultSecurityKey.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)), "RS256")
{
    CryptoProviderFactory = new CryptoProviderFactory() { CustomCryptoProvider = new KeyVaultCryptoProvider() }
});

But it is not clear for me, what really AuthenticationCallback is and how to implement that and if i will be able to use that in Azure in web app or azure function?

michasaucer
  • 4,562
  • 9
  • 40
  • 91
  • AuthenticationCallback is a delegate function which accepts authority, resource, scope and returns access token for the service. – Nayan May 25 '22 at 12:46
  • check if this helps. https://vmsdurano.com/-net-core-3-1-signing-jwt-with-rsa/ (keys in configuration files) KeyVault for OAuth2 Client Creds - https://github.com/mrochon/keyvault (keys lies in key vault) – Nayan May 25 '22 at 12:50

1 Answers1

1
  • Firstly, a JWT token consists of 3 parts (Header, Payload and Signature) and all those 3 parts are Base64UriEncoded.

  • To get the Signature you need to generate header and payload, then combine them by dot.**

  • Below is the sample code to verify JWT using Azure kay Vault.

const key = await this.keyClient.getKey(this.KEY_NAME);
 const cryptClient = new CryptographyClient(key, new DefaultAzureCredential());
const util =require('util')
const base64 = require('base64url');
const JWT=""
    const jwtHeader = JWT.split('.')[0];
    const jwtPayload = JWT.split('.')[1];
    const jwtSignature = JWT.split('.')[2];
    const signature = base64.toBuffer(jwtSignature)
    const data = util.format('%s.%s', jwtHeader, jwtPayload);
    const hash = crypto.createHash('sha256');
    const digest = hash.update(data).digest()
const verified =await cryptClient.verify("RS256",digest,signature)
  • Here are few SO threads with related discussions. SO1, SO2 and SO3
SaiSakethGuduru
  • 2,218
  • 1
  • 5
  • 15