Exemplo n.º 1
0
        public void GivenWrongAuthenticationResult_WhenMapping_ThenGetFailure(AuthenticateResult authResult)
        {
            var dto = TokenResponseDto.Create(authResult, Username);

            dto.Failure.Should().NotBeNull();
            ((int)dto.Failure).Should().Be((int)authResult);
        }
Exemplo n.º 2
0
        public void GivenGoodAuthenticationResult_WhenMapping_ThenGetSuccess()
        {
            var authResult = AuthenticateResult.Ok;

            var dto = TokenResponseDto.Create(authResult, Username);

            dto.Failure.Should().BeNull();
        }
        public async Task <IActionResult> Post([FromBody] AuthenticationDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var responseDto = await Envelope(async() =>
            {
                var result   = await _identityService.Authenticate(dto.Username, dto.Password);
                var response = TokenResponseDto.Create(result, dto.Username);

                if (result == AuthenticateResult.Ok)
                {
                    var identity = await _identityRepository.GetByEmail(dto.Username);
                    var claims   = new[]
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, identity.Id.ToString()),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(ClaimTypes.Email, identity.Email),
                        new Claim(ClaimTypes.Name, identity.Username),
                        new Claim(ClaimTypes.Actor, identity.IdType.ToString()),
                        new Claim(ClaimTypes.Role, IdentityRoles.ToRole(identity.IdType))
                    };

                    var token = new JwtSecurityToken(
                        _configurationProvider.TokenConfiguration.Issuer,
                        _configurationProvider.TokenConfiguration.Audience,
                        claims,
                        expires: DateTime.UtcNow.AddHours(1),
                        signingCredentials: new SigningCredentials(
                            _configurationProvider.TokenConfiguration.SigningKey,
                            SecurityAlgorithms.HmacSha256));

                    response.Token = new JwtSecurityTokenHandler().WriteToken(token);
                }

                return(response);
            });

            responseDto.IsSuccessful = responseDto.Payload.Token.HasValue();
            return(Ok(responseDto));
        }