如何在 Asp.NetCore WebApi 的 JWT 声明中传递和对象,例如,假设我想传递一个带有 ID 和名称的 Gender 对象。
private IActionResult GenerateJwtToken(string email, ApplicationUser user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Email, user.Email.ToString()),
new Claim(ClaimTypes.GivenName, user.FirstName.ToString()),
new Claim(ClaimTypes.UserData, user.LastName.ToString()),
new Claim(ClaimTypes.StreetAddress, user.Address.ToString()),
new Claim(ClaimTypes.DateOfBirth, user.DateOfBirth.ToString()),
new Claim(ClaimTypes.Rsa, user.FileName.ToString()),
new Claim(ClaimTypes.Gender, user.Sex.ToString()),
new Claim(ClaimTypes.Country, user.Country.ToString()),
new Claim(ClaimTypes.StateOrProvince, user.state.ToString()),
new Claim(ClaimTypes.Locality, user.LGA.ToString()),
new Claim(ClaimTypes.Hash, user.HairColor.ToString()),
new Claim(ClaimTypes.Sid, user.GenoType.Name.ToString()),
new Claim(ClaimTypes.Spn, user.BloodGroup.ToString()),
new Claim(ClaimTypes.System, user.Religion.ToString()),
new Claim(ClaimTypes.NameIdentifier, user.NKName.ToString()),
new Claim(ClaimTypes.OtherPhone, user.NKPhoneNumber.ToString()),
new Claim(ClaimTypes.SerialNumber, user.NKAddress.ToString()),
new Claim(ClaimTypes.GroupSid, user.NKRelationship.ToString()),
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new{ token = tokenString });
}
请如果有任何更好的方法来获取除了索赔之外的当前登录用户详细信息,我很想知道它。提前致谢
[HttpGet("/api/profile")]
public IActionResult Index()
{
var claimIdentity = this.User.Identity as ClaimsIdentity;
IEnumerable<Claim> claims = claimIdentity.Claims;
var model = new IndexViewModel
{
Id = claimIdentity.FindFirst(ClaimTypes.Name).Value,
Email = claimIdentity.FindFirst(ClaimTypes.Email).Value,
FirstName = claimIdentity.FindFirst(ClaimTypes.GivenName).Value,
LastName = claimIdentity.FindFirst(ClaimTypes.UserData).Value,
Address = claimIdentity.FindFirst(ClaimTypes.StreetAddress).Value,
DateOfBirth = claimIdentity.FindFirst(ClaimTypes.DateOfBirth).Value,
FileName = claimIdentity.FindFirst(ClaimTypes.Rsa)?.Value,
};
return Ok(model);
}