コード例 #1
0
        public async Task <string> GenerateJwt(LoginDTO dto)
        {
            var user = await _efCoreAccountRepository.GetUserByEmail(dto);

            if (user == null)
            {
                throw new NotFoundExpection("Invalid user name or password");
            }

            var result = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, dto.Password);

            if (result == PasswordVerificationResult.Failed)
            {
                throw new BadRequestException("Invalid user name or password");
            }


            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, $"{user.Email}"),
                new Claim(ClaimTypes.Role, $"{user.Role.Name}"),
            };

            if (!string.IsNullOrEmpty(user.Nationality))
            {
                claims.Add(new Claim("Nationality", user.Nationality));
            }

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authenticationSettings.JwtKey));
            var cred    = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(_authenticationSettings.JwtExpireDays);

            var token = new JwtSecurityToken(_authenticationSettings.JwtIssuer,
                                             _authenticationSettings.JwtIssuer,
                                             claims,
                                             expires: expires,
                                             signingCredentials: cred);

            var tokenHandler = new JwtSecurityTokenHandler();



            return(tokenHandler.WriteToken(token));
        }