本文介绍了Azure KeyVault-签名JWT令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用Azure Keyvault存储我的应用程序的私钥。



我有一个用例,我需要用RSA私钥对JWT令牌进行签名。



当我在应用程序内存中拥有私钥时,这很简单,
我会那样做

  var令牌=新的JwtSecurityToken(
发行者,
...,
索赔,
...,
...,
signingCredentials_PrivateKey);

现在我开始使用Azure Keyvault,我想看看是否可以通过以下方式签署JWT令牌 KeyVaultClient.SignAsync 方法。



类似于

  KeyVaultClient client = ... ; 
var令牌=新的JwtSecurityToken(
发行者,
...,
索赔,
...,
...);
var tokenString = client.SignAsync(myKeyIdentifier,令牌);


解决方案

首先,JWT令牌包括三个部分:标头,有效载荷和签名。它们都是Base64UrlEncoded。



您可以按照以下方式获得签名:

  HMAC-SHA256(
base64urlEncoding(header)+'。'+ base64urlEncoding(payload),
secret

因此,您需要生成标头和有效负载,将它们按点组合,计算散列,然后即可获取签名。



以下是供您参考的示例:

  var byteData = Encoding.Unicode.GetBytes(base64urlEncoding(header)+。 + base64urlEncoding(payload)); 
var hasher = new SHA256CryptoServiceProvider();
var摘要= hasher.ComputeHash(byteData);
var签名=等待keyClient.SignAsync(keyIdentifier, RS256,摘要);
var token = base64urlEncoding(header)+。 + base64urlEncoding(有效载荷)+。 + base64urlEncoding(signature)

的Wiki

I began using Azure Keyvault to store private keys for my application.

I have a use case where I need to sign a JWT token with an RSA private key.

When I had the private key in my application memory, it was easy,I would just do that

var token = new JwtSecurityToken(
                issuer,
                ...,
                claims,
                ...,
                ...,
                signingCredentials_PrivateKey);

Now that I began to use Azure Keyvault, I want to see if it's possible to sign JWT tokens via the KeyVaultClient.SignAsync method.

Something along the lines of

KeyVaultClient client = ...;
var token = new JwtSecurityToken(
                issuer,
                ...,
                claims,
                ...,
                ...);
var tokenString = client.SignAsync(myKeyIdentifier, token);
解决方案

First, a JWT token consists of three parts: Header, Payload and Signature. All of them are Base64UrlEncoded.

You can get the signature as following:

HMAC-SHA256(
 base64urlEncoding(header) + '.' + base64urlEncoding(payload),
 secret
)

So, you need to generate the header and payload, combine them by dot, compute the hash, and then you can get the signature.

Here is a sample for your reference:

var byteData = Encoding.Unicode.GetBytes(base64urlEncoding(header) + "." + base64urlEncoding(payload));
var hasher = new SHA256CryptoServiceProvider();
var digest = hasher.ComputeHash(byteData);
var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
var token = base64urlEncoding(header) + "." + base64urlEncoding(payload) + "." + base64urlEncoding(signature)

The official SDK documentation for SignAsync

Wiki for JWT

这篇关于Azure KeyVault-签名JWT令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 22:01