Azure KeyVault - 签署 JWT 令牌 [英] Azure KeyVault - Sign JWT Token

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

问题描述

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

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

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

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

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

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.

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

推荐答案

首先,一个 JWT 令牌由三部分组成:Header、Payload 和 Signature.它们都是 Base64UrlEncoded.

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

你可以得到如下签名:

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

所以,你需要生成header和payload,通过dot组合,计算hash,然后就可以得到签名了.

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)

签名异步

JWT

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

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