如何在 .net 核心中添加声明配置文件?



我声明了jwt,其内容基于UserViewModelLogin.cs,这是Dto。如何从配置文件模型声明 jwt.cs

控制器

[HttpPost("Login")]
public async Task<IActionResult> Login(UserViewModelLogin userViewModelLogin)
{
var userFromRepo = await _repo.Login(userViewModelLogin.Username.ToLower(), userViewModelLogin.Password, userViewModelLogin.Role);
if (userFromRepo == null)
return Unauthorized("Maaf Username atau Password Anda Salah :(");
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, userFromRepo.IdUser.ToString()),
new Claim(ClaimTypes.Name, userFromRepo.Username),
new Claim(ClaimTypes.Role, userFromRepo.Role),
new Claim("IdProfile", userFromRepo.IdProfile.ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8
.GetBytes(_config.GetSection("AppSettings:Token").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var role = userFromRepo.Role.ToString();
return Ok(new
{
token = tokenHandler.WriteToken(token)
});
}

用户视图模型登录

public class UserViewModelLogin
{
public string Username { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}

用户模型

public class UserModel
{
[Key]
public int IdUser { get; set; }
public string Username { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
public string Role { get; set; }
public int IdProfile { get; set; }
}

轮廓模型

[Key]
public int IdProfile { get; set; }
public string FullName { get; set; }       
public int KTPNumber { get; set; }
public string Address { get; set; }
public int NumberPhone { get; set; }
public string Email { get; set; }
public DateTime Created { get; set; }
public string Image { get; set; }
public int Province_id { get; set; }
public int Regencies_id { get; set; }
public int District_id { get; set; }
public int Villages_id { get; set; }
public ProfileModel()
{          
this.Created = DateTime.Now;
}
}

我有两个模型,用户模型.cs和配置文件模型.cs,然后用户登录并生成 jwt 令牌输出。 在这里,我想令牌声明 jwt 包含来自配置文件模型.cs的配置文件数据。

你已经有

new Claim("IdProfile", userFromRepo.IdProfile.ToString()),

然后只需在它下面添加

new Claim("FullName", userFromRepo.FullName.ToString()),
new Claim("KTPNumber", userFromRepo.KTPNumber.ToString()),
.....

最新更新