我具有根据令牌参数创建令牌的功能,
每次调用函数时,JwtSecurityTokenHandler tokenHandler
将包含不同的参数。
我认为我写的方式还不够好。有什么建议吗?
private string CreateUserToken(string memberId, EmailOrPhone emailOrPhone, ENeedUpdateOrFinishRegistration newOrUpdate, string value)
{
var newOrupdate = new Claim("actionName", "Register");
if (newOrUpdate.Equals(ENeedUpdateOrFinishRegistration.NeedUpdate))
{
newOrupdate = new Claim("actionName", "Update");
}
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptorByChoice = new SecurityTokenDescriptor();
var key = Encoding.ASCII.GetBytes("MySecret_Nofshonit");
switch (emailOrPhone)
{
case (EmailOrPhone.Email):
{
tokenDescriptorByChoice.Subject = new ClaimsIdentity(new Claim[]
{
new Claim("memberId", memberId.ToString()),
new Claim("creationDate", DateTime.Now.ToString("ddMMyyyy")),
new Claim("expiredDate", DateTime.Now.AddHours(12).ToString("ddMMyyyy")),
newOrupdate,
new Claim("value", value),
new Claim("fieldName", "Phone")
});
break;
}
case (EmailOrPhone.Phone):
{
tokenDescriptorByChoice.Subject = new ClaimsIdentity(new Claim[]
{
new Claim("memberId", memberId.ToString()),
new Claim("creationDate", DateTime.Now.ToString("ddMMyyyy")),
new Claim("expiredDate", DateTime.Now.AddHours(48).ToString("ddMMyyyy")),
newOrupdate,
new Claim("value", value),
new Claim("fieldName", "Email")
});
break;
}
default:
break;
}
tokenDescriptorByChoice.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);
var token = tokenHandler.CreateToken(tokenDescriptorByChoice);
var tokenString = tokenHandler.WriteToken(token);
var encryptedTokenString = Cryptor.Encrypt(tokenString);
return encryptedTokenString;
}