예제 #1
0
        public async Task <AuthenticationResponse> Authenticate([FromBody] AuthenticationRequest request)
        {
            (bool isAuthenticated, int userId, string errorMessage) = await _usersRepository.IsAuthenticated(request.Username, request.Password);

            if (isAuthenticated)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
                    new Claim(ClaimTypes.Name, request.Username)
                };

                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigProvider.SecurityKey));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: "localhost:8001",
                    audience: "localhost:8002",
                    claims: claims,
                    expires: DateTime.Now.AddMonths(1),
                    signingCredentials: creds);

                var authenticatedUser = new AuthenticatedUser(userId, request.Username, new JwtSecurityTokenHandler().WriteToken(token));

                return(AuthenticationResponse.CreateSuccessfulResult(authenticatedUser));
            }

            return(AuthenticationResponse.CreateFailedResult(errorMessage));
        }