我正在努力想出一种在产品中标准化JWT创建的方法。 以下是我遇到的两个实现
使用JwtSecurityToken,其中受众可以为null,在此实现中,我们使用特定于客户端的GUID作为受众ID
string audienceId = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null;
if (string.IsNullOrWhiteSpace(audienceId)) throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience");
ClientDataModel audience = ClientStore.FindAudience(audienceId);
string symmetricKeyAsBase64 = audience.Base64Secret;
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
var signingKey = new HmacSigningCredentials(keyByteArray);
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
//Generate Token based on the Passed information as Parameters
var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
//Write Token in the JWT Format
var jwt = handler.WriteToken(token);
return jwt;
使用SecurityTokenDescriptor,其中必须使用AppliesToAddress,并在未提供错误时抛出错误。根据oauth规范,受众是可选参数
var tokenHandler = new JwtSecurityTokenHandler();
var now = DateTime.UtcNow;
string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["AudienceSecret"];
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
var signingKey = new HmacSigningCredentials(keyByteArray);
// Token Creation
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, ""),
}),
TokenIssuerName = ConfigurationManager.AppSettings["Issuer"],
AppliesToAddress = ConfigurationManager.AppSettings["AppliesToAddress"],
Lifetime = new Lifetime(now, now.AddMinutes(Int32.Parse((string)ConfigurationManager.AppSettings["TokenValidFor"]))),
SigningCredentials = signingKey
};
JwtSecurityToken token = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;
return token.RawData;
有人可以建议使用哪一个吗?