如何将X509SigningCredentials与System.IdentityModel.Tokens.Jwt.Jw
本文关键字:IdentityModel Tokens Jwt Jw System X509SigningCredentials | 更新日期: 2023-09-27 17:57:52
我想使用Microsoft IdentityModel创建我自己的JWT令牌。这个库似乎很好,但没有足够的文档:-(
所以我的问题是我不知道如何将X509CigningCredentials转换为SigningCredential,所以我无法创建JwtHeader。。。
这是我的代码:
public void GenereToken()
{
var certThumbPrint = "ACCB5050C2591FF9CB9F90D71D8B96BE13DC9320";
X509Store certStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbPrint, false);
certStore.Close();
var header = new System.IdentityModel.Tokens.Jwt.JwtHeader(new X509SigningCredentials(certCollection[0]));
var payload = new JwtPayload
{
{"iss", "a5ghgde64-e8g4d-48ga-beg1-56e293d09a69"},
{"scope", "example.com"},
{"aud", "example.com"},
{"iat", 1441698079},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var cielToken = handler.WriteToken(secToken)
}
有人能帮我吗?
试试这个代码
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Tokens;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
GenereToken();
}
public static void GenereToken()
{
var certThumbPrint = "95 2f 5e ca 7c d0 a3 f0 6c ca 7d e4 0a 24 7a 2c c3 42 f5 f6";
X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbPrint, false);
certStore.Close();
var securityKey = new X509SecurityKey(certCollection[0]);
var algorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
var header = new JwtHeader(new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, algorithm));
var payload = new JwtPayload
{
{"iss", "a5ghgde64-e8g4d-48ga-beg1-56e293d09a69"},
{"scope", "example.com"},
{"aud", "example.com"},
{"iat", 1441698079},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var cielToken = handler.WriteToken(secToken);
}
}
}
packages.config的内容是
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.IdentityModel.Logging" version="1.0.0" targetFramework="net461" />
<package id="Microsoft.IdentityModel.Tokens" version="5.0.0" targetFramework="net461" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net461" />
<package id="System.IdentityModel.Tokens.Jwt" version="5.0.0" targetFramework="net461" />
</packages>
我用这个页面来获取算法名称。