Esempio n. 1
0
        public UserDTO Authenticate(string username, string password)
        {
            var user = _userFinder.getByUsername(username);

            if (user == null)
            {
                return(null);
            }

            if (!HashHandle.CheckMatch(user.Password, password))
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_authSettings.SecretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var userDTO = _baseService.ConvertToDTO <User, UserDTO>(user);

            userDTO.Token    = tokenHandler.WriteToken(token);
            userDTO.Password = null;

            return(userDTO);
        }