如何生成token
private Token GetJwt(User user)
{
var now = DateTime.UtcNow;
var claims = new Claim[]
{
new Claim(MyClaimTypes.UserId,user.ID.ToString(),ClaimValueTypes.Integer32),
new Claim(MyClaimTypes.UserName,user.UserName),
//new Claim(MyClaimTypes.RoleId,user.RoleID.ToString(),ClaimValueTypes.Integer32),
new Claim(MyClaimTypes.RoleCode,user.RoleCode),
new Claim(MyClaimTypes.DepartmentId,user.DepartmentID.ToString(),ClaimValueTypes.Integer32),
new Claim(MyClaimTypes.DepartmentName,user.DepartmentName??""),
//new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(),
ClaimValueTypes.Integer64)
};
var jwt = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
notBefore: now,
expires: now.Add(_options.Expiration),
signingCredentials: _options.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler()
.WriteToken(jwt);
return new Token
{
access_token = encodedJwt,
expires_in = (int)_options.Expiration.TotalSeconds,
token_type = "Bearer"
};
}
//获取token中的参数
public static UserInfoLogin ConvertToUserInfo(ClaimsPrincipal claimsPrincipal)
{
int.TryParse(claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.ID)?.Value, out int id);
string roles = claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.Roles)?.Value;
string loginName = claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.LoginName)?.Value;
string passWord = claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.PassWord)?.Value;
string userName = claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.UserName)?.Value;
string telephone = claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.Telephone)?.Value;
int.TryParse(claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.UserType)?.Value, out int userType);
int.TryParse(claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.AdminAddressType)?.Value, out int adminAddressType);
int.TryParse(claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.Strength)?.Value, out int strength);
string Model = claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.Module)?.Value;
string socialNum = claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.SocialNum)?.Value;
int.TryParse(claimsPrincipal.Claims.FirstOrDefault(m => m.Type == ClaimKeys.AddressType)?.Value,out int addressType);
return new UserInfoLogin
{
ID = id,
Roles = roles,
LoginName = loginName,
UserName = userName,
Telephone = telephone,
UserType = userType,
AdminAddressType = adminAddressType,
Strength = strength,
Module = Model,
SocialNum= socialNum,
AddressType= addressType,
PassWord = passWord,
};
}