Exemplo n.º 1
0
        /// <summary>
        /// This method Authenticate user and password details
        /// </summary>
        /// <param name="username">The username</param>
        /// <param name="password">The password</param>
        /// <returns></returns>
        public async Task <User> AuthenticateAsync(string username, string password)
        {
            UserValidation.ValidateUserName(username);
            UserValidation.ValidatePassword(password);
            // return null if user not found
            var applicationUser = await userDataService.FindUserByName(username);

            if (applicationUser != null && await userDataService.CheckPasswordAsync(applicationUser, password))
            {
                // authentication successful so generate jwt token
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, applicationUser.Id.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);

                User user = new User();
                user.Token    = tokenHandler.WriteToken(token);
                user.Username = applicationUser.UserName;
                user.email    = applicationUser.Email;
                return(user);
            }
            return(null);
        }