Beispiel #1
0
        public async Task <AuthenticatedUserReadModel> Authenticate(string userName, string password)
        {
            AccountByUserNameQuery accountByUserNameQuery = new AccountByUserNameQuery
            {
                UserName = userName,
            };

            AccountWithCredentialsModel account = await _query.Query <Task <AccountWithCredentialsModel>, AccountByUserNameQuery>(accountByUserNameQuery);

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

            if (!await _passwordHasher.CheckHash(password, account.PasswordHash, account.PasswordSalt))
            {
                return(null); // todo throw exception
            }
            byte[] key = Encoding.ASCII.GetBytes(_jwtSettings.Key);
            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, account.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddMinutes(_jwtSettings.ExpiryMinutes),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken        token        = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);

            return(new AuthenticatedUserReadModel
            {
                Token = tokenHandler.WriteToken(token),
                Name = account.Name,
                Surname = account.Surname
            });
        }