public async Task <AuthenticatedUserDto> AuthorizeAsync(LoginDto loginDto) { var userEntity = await _tripFlipDbContext .Users .AsNoTracking() .Include(user => user.ApplicationRoles) .ThenInclude(usersRoles => usersRoles.ApplicationRole) .FirstOrDefaultAsync(user => user.Email == loginDto.Email); EntityValidationHelper.ValidateEntityNotNull( userEntity, ErrorConstants.UserNotFound); bool isPasswordVerified = PasswordHasherHelper .VerifyPassword(loginDto.Password, userEntity.PasswordHash); if (!isPasswordVerified) { throw new ArgumentException(ErrorConstants.PasswordNotVerified); } AuthenticatedUserDto authenticatedUserDto = _mapper.Map <AuthenticatedUserDto>(userEntity); authenticatedUserDto.Token = JsonWebTokenHelper.GenerateJsonWebToken( userIncludingRoles: userEntity, issuer: _jwtConfiguration.Issuer, audience: _jwtConfiguration.Audience, secretKey: _jwtConfiguration.SecretKey, tokenLifetime: _jwtConfiguration.TokenLifetime); return(authenticatedUserDto); }
public async Task <ActionResult <AuthenticatedUserDto> > LoginAsync(LoginDto model) { var user = await _userManager.FindByNameAsync(model.UserName); if (user is null) { return(NotFound()); } bool result = await _userManager.CheckPasswordAsync(user, model.Password); if (!result) { return(Unauthorized()); } string token = await GenerateJwtToken(user); string role = user.Claims.FirstOrDefault(x => x.ClaimType == "role").ClaimValue; var authenticatedUser = new AuthenticatedUserDto { Username = user.UserName, IsAdmin = role == "Admin" ? true : false, Token = token }; return(Ok(authenticatedUser)); }
public WSReceitaController(IConfiguration configuration, IUserPermissionService serviceUserPermission, AuthenticatedUserDto authenticatedUser ) { _configuration = configuration; _serviceUserPermission = serviceUserPermission; _authenticatedUser = authenticatedUser; }
public UserController(IUserService service, ICompanyService serviceCompany, IUserPermissionService serviceUserPermission, AuthenticatedUserDto authenticatedUser ) { _service = service; _serviceCompany = serviceCompany; _serviceUserPermission = serviceUserPermission; _authenticatedUser = authenticatedUser; }
public PermissionController(IPermissionService service, IUserPermissionService serviceUserPermission, IUserService serviceUser, AuthenticatedUserDto authenticatedUser ) { _service = service; _serviceUserPermission = serviceUserPermission; _serviceUser = serviceUser; _authenticatedUser = authenticatedUser; }
public IHttpActionResult Login(LoginRequest loginRequest) { UserLoginManager userLoginManager = new UserLoginManager(); AuthenticatedUserDto authenticatedUserDto = userLoginManager.TryLogin(loginRequest); if (authenticatedUserDto == null) { return(Unauthorized()); } return(Ok(authenticatedUserDto)); }
public async Task Authenticate_WithValidUser_ReturnsOk() { // Arrange CreateUser user = new CreateUser() { FirstName = "Test", LastName = "User", Email = "*****@*****.**", Password = "******" }; UpdateUserInfo updateUserInfo = new UpdateUserInfo(); var requestContent = new StringContent( JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); // Act HttpResponseMessage createUserResponse = await _client.PutAsync("api/user", requestContent); string createdUserSerialized = await createUserResponse.Content.ReadAsStringAsync(); User createdUser = JsonConvert.DeserializeObject <User>(createdUserSerialized); createUserResponse.StatusCode.Should().Be(HttpStatusCode.OK); createdUser.Id.Should().NotBe(Guid.Empty); AuthenticateUser authenticateUser = new AuthenticateUser { Email = "*****@*****.**", Password = "******" }; var authRequestContent = new StringContent( JsonConvert.SerializeObject(authenticateUser), Encoding.UTF8, "application/json"); HttpResponseMessage authenticateResponse = await _client.PostAsync("api/user/authenticate", authRequestContent); authenticateResponse.StatusCode.Should().Be(HttpStatusCode.OK); string authenticatedUserSerialized = await authenticateResponse.Content.ReadAsStringAsync(); AuthenticatedUserDto authenticatedUserDto = JsonConvert.DeserializeObject <AuthenticatedUserDto>(authenticatedUserSerialized); authenticatedUserDto.User.Should().NotBe(null); authenticatedUserDto.User.Id.Should().NotBe(Guid.Empty); authenticatedUserDto.WebToken.Token.Should().NotBe(string.Empty); authenticatedUserDto.WebToken.Token.Should().NotBe(null); }
public AuthenticatedUserDto TryLogin(LoginRequest loginRequest) { User user; if (!IsUserAuthenticated(loginRequest, out user)) { return(null); } AuthenticatedUserDto authenticatedUserDto = Mapper.Map <AuthenticatedUserDto>(user); string securityToken = JwtTokenCreator.CreateToken(user, ConfigurationManager.AppSettings["SecretSignatureKey"]); authenticatedUserDto.Token = securityToken; return(authenticatedUserDto); }
public IActionResult Authentication([FromBody] AuthenticateUserDto userAuthentication) { if (userAuthentication == null) { return(this.BadRequest(this.NotificationFactory.Error($"{nameof(userAuthentication)} not found."))); } AuthenticatedUserDto authenticatedUserDto = this.AuthenticationService.AuthenticateUser(userAuthentication); if (!authenticatedUserDto.Authenticated) { return(this.BadRequest(this.NotificationFactory.Error(authenticatedUserDto.Error))); } return(this.Ok(this.NotificationFactory.Success(authenticatedUserDto.UserSystem))); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto request) { AuthenticateDtoValidator validator = new AuthenticateDtoValidator(); ValidationResult validationResult = await validator.ValidateAsync(request); if (!validationResult.IsValid) { throw new EntityValidationException("Authentication", request, validationResult.Errors); } AuthenticatedUserDto userDto = (request.GrantType == "password") ? await _mediator.Send(new Authenticate { Username = request.Username, Password = request.Password }) : await _mediator.Send(new AuthWithRefreshToken { Token = request.Token }); return(CreateResponse(HttpStatusCode.OK, userDto)); }
public async Task <IActionResult> Login([FromBody] LoginDto loginDto) { var user = await this._context.Users .Include(c => c.UserGroups) .ThenInclude(c => c.Group) .ThenInclude(c => c.GroupPrivileges) .ThenInclude(c => c.Privileg) .Where(c => c.UserName == loginDto.UserName).FirstOrDefaultAsync(); if (user == null) { return(Conflict()); } if (!MD5Hash.VerifyMd5Hash(loginDto.Password, user.Password)) { return(Conflict()); } var climes = new List <Claim>(); var privlileges = user.UserGroups.SelectMany(c => c.Group.GroupPrivileges.Select(c => c.Privileg)).Distinct(); foreach (var item in privlileges) { climes.Add(new Claim(ClaimTypes.Role, item.SysName)); } climes.Add(new Claim("UserID", user.Id.ToString())); if (!user.CanWorkAsAgent) { climes.Add(new Claim("Type", "Employee")); } else { climes.Add(new Claim("Type", "Agent")); } var haveTreasury = await _treasuryService.Any(c => c.Id == user.Id && c.IsActive); if (haveTreasury) { climes.Add(new Claim("treasury", true.ToString())); } else { climes.Add(new Claim("treasury", false.ToString())); } climes.Add(new Claim(ClaimTypes.Name, user.Name)); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(climes), Expires = DateTime.UtcNow.AddHours(14), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authnetication")), SecurityAlgorithms.HmacSha256Signature) }; var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); AuthenticatedUserDto authenticatedUserDto = _mapper.Map <AuthenticatedUserDto>(user); authenticatedUserDto.Token = token; authenticatedUserDto.Policy = user.CanWorkAsAgent ? "Agent" : "Employee"; authenticatedUserDto.HaveTreasury = haveTreasury; return(Ok(authenticatedUserDto)); }
public UserPermissionController(IUserPermissionService service, AuthenticatedUserDto authenticatedUser) { _service = service; _authenticatedUser = authenticatedUser; }
public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticatedUserDto userData) { var jwtToken = await _userService.AuthenticateAsync(userData.Username, userData.Password); return(Ok(jwtToken)); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticateUser request) { AuthenticatedUserDto authenticatedUser = await _mediator.Send(request); return(Ok(authenticatedUser)); }