Witam, pisze prostą aplikację i chcialem dodać logowanie, może mi ktoś odpowiedziec na poniższe pytania pod kodem? dotyczą w sumie tylko czerwonej częsci kodu, dodałem całą logikę aby było wiadomo o co chodzi
[HttpPost("login")]
public string Login([FromBody] LoginDTO loginDTO)
{
//this logic has to be move into service
var user = _myLibrusDbContext.Users
.Include(x => x.Role)
.FirstOrDefault(x => x.Mail == loginDTO.Email);
// logic if user exist
//check if password is okey
var result = _hasher.VerifyHashedPassword(user, user.PasswordHashed, loginDTO.Password);
if(result == PasswordVerificationResult.Failed)
{
throw new BadHttpRequestException("Bad password or username");
}
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
new Claim(ClaimTypes.Role, user.Role.RoleName),
new Claim("email", user.Mail.ToString()),
};
//here we generate private key
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authenticationSettins.JwtKey));
//here we generate credencials
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//here we generate expires time of token
var expires = DateTime.Now.AddDays(_authenticationSettins.JwtExpireDays);
// issuer, audience( clients of api)
var token = new JwtSecurityToken(
_authenticationSettins.JwtIssuer,
_authenticationSettins.JwtIssuer,
claims,
expires: expires,
signingCredentials: cred);
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(token);
Czy ktoś może mi wyjaśnić co dokladnie przypisywanie jest do zmienney key, a co do cred?
co to są te credencials? I dlaczego wkładamy tam key skoro jest on juz zaszyfrowany? móglby mi ktoś to wytlumaczyć?
PS. wiem, że logiki sie nie pisze w kontrolerze, to tylko w celach testowych aby bylo szybciej