public AuthenticationDTO AuthenticateGetToken(TokenDTO tokenDTO) { string _refreshTokenold = HttpUtility.UrlDecode(tokenDTO.Refresh_Token); string _refreshToken = refreshtoken.GenerateToken(tokenDTO); RefreshTokenDTO refauth = new RefreshTokenDTO { Authorization = _refreshTokenold }; AuthenticationDTO auth = new AuthenticationDTO(); try { // ValidationResult results = refreshvalidation.Validate(refauth); Authorize authorize = oauth.Authorize.Where(x => x.Code == refauth.Authorization).FirstOrDefault(); User user = oauth.User.SingleOrDefault(x => x.UserId == authorize.UserId); UserDTO userDTO = mapper.Map <UserDTO>(user); auth.token_type = config["TokenType"]; auth.access_token = JWTToken.GenerateToken(tokenDTO); auth.refresh_token = HttpUtility.UrlEncode(_refreshToken); authorize.Code = _refreshToken; oauth.SaveChanges(); } catch (Exception ex) { Log.Log.Error(ex, TokenConstants.InvalidUser); throw new InvalidUserException(TokenConstants.InvalidUser); } return(auth); }
public async Task Test_PostAuth() { //Arrange. TokenDTO mockToken = new TokenDTO() { Login = "******", Name = "Yago", Token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InlhZ29oZiIsIm5iZiI6MTU0NzYwNjQ5NywiZXhwIjoxNTQ3NjkyODk3LCJpYXQiOjE1NDc2MDY0OTd9.qzmJSEvtoHphSpOkFJ81mN2FqeiyXk47zo3euVFxACk" }; AuthenticationDTO authenticationData = new AuthenticationDTO() { Login = "******", Password = "******" }; this._userServiceMock .Setup(srv => srv.GenerateTokenAsync(authenticationData)) .Returns(Task.FromResult(mockToken)); //Act. var result = await this._usersController.PostAuth(authenticationData); var okResult = result as OkObjectResult; //Assert. Assert.IsNotNull(okResult); Assert.IsInstanceOfType(okResult.Value, typeof(TokenDTO)); Assert.AreEqual(mockToken, okResult.Value as TokenDTO); }
/// <summary> Authenticates the user with the given credentials.</summary> /// <param name="credentials"> The user credentials.</param> /// <returns> Authentication result.</re public async Task <AuthenticationResult> AuthenticateAsync(AuthenticationDTO credentials) { var userValidation = await _userManagementService.ValidateUserAsync(credentials.Email, credentials.Password); if (userValidation.Result != AuthenticationResults.Succes) { return(new AuthenticationResult(userValidation.Result)); } DateTime now = DateTime.UtcNow; var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, userValidation.User.ToString()), new Claim("authorized", (!userValidation.Has2FaEnabled)? "true" : "false") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenSettings.Secret)); var jwtCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwt = new JwtSecurityToken( issuer: _tokenSettings.Issuer, audience: _tokenSettings.Audience, claims: claims, notBefore: now, expires: now.AddMinutes(_tokenSettings.AccesExpiration), signingCredentials: jwtCredentials ); var authenticationResult = new AuthenticationResult(new JwtSecurityTokenHandler().WriteToken(jwt)); return(authenticationResult); }
public bool Authenticate(object existing, object credentials) { AuthenticationDTO exisitngDTO = existing as AuthenticationDTO; AuthenticationDTO credentialsDTO = credentials as AuthenticationDTO; return(exisitngDTO.Equals(credentialsDTO)); }
public async Task <string> GetToken() { string token = null; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; var client = new HttpClient(); client.BaseAddress = new Uri(_baseUri); client.DefaultRequestHeaders.Add("Accept", "application/json"); var authDTO = new AuthenticationDTO { ClientId = _clientId, ClientSecret = _clientSecret }; var jsonContent = JsonConvert.SerializeObject(authDTO); var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"); var route = _requestPrefix + Routes.AUTH; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, route); request.Content = httpContent; await client.SendAsync(request) .ContinueWith(responseTask => { var responseMesssage = responseTask.Result.Content.ReadAsStringAsync().Result; token = JObject.Parse(responseMesssage)["access_token"].ToString(); }); return(token); }
public async Task <AuthenticationresponseDTO> SignIn(AuthenticationDTO userFromAuthentication) { try { var content = JsonConvert.SerializeObject(userFromAuthentication); var bodyContent = new StringContent(content, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("api/account/signin", bodyContent); var contentTemp = await response.Content.ReadAsStringAsync(); // Enitity to DTO convert is alrdy done in repository var result = JsonConvert.DeserializeObject <AuthenticationresponseDTO>(contentTemp); if (response.IsSuccessStatusCode) { await _localStorage.SetItemAsync(SD.Local_Token, result.Token); await _localStorage.SetItemAsync(SD.Local_UserDetails, result.userDTO); ((AuthStateProvider)_authenticationStateProvider).NotifyUserLoggedIn(result.Token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token); return(new AuthenticationresponseDTO { IsAuthSuccessful = true }); } else { return(result); } } catch (Exception e) { throw new Exception(e.Message); } }
public async Task <AuthenticationDTO> Authenticate(SignInDTO credentials) { User user = await _userManager.FindByEmailAsync(credentials.Login) ?? await _userManager.FindByNameAsync(credentials.Login); if (user == null) { throw new NotFoundException("A user with the provided login does not exist."); } if (!await _userManager.CheckPasswordAsync(user, credentials.Password)) { throw new UnauthorizedException("Failed to sign in with the provided login/password combination. Try again."); } JwtSecurityToken token = await GenerateToken(user); string tokenString = new JwtSecurityTokenHandler().WriteToken(token); AuthenticationDTO userInfo = new AuthenticationDTO() { Id = Int32.Parse(token.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value), Username = token.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value, Roles = token.Claims.Where(c => c.Type == ClaimTypes.Role) .Select(r => r.Value).ToArray(), Token = tokenString, RefreshToken = await GenerateRefreshToken(user) }; return(userInfo); }
public async Task <AuthenticationResponseDTO> Login(AuthenticationDTO user) { var content = JsonConvert.SerializeObject(user); var bodyContent = new StringContent(content, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("/api/account/signin", bodyContent); var contentTemp = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject <AuthenticationResponseDTO>(contentTemp); if (response.IsSuccessStatusCode) { await _localStorageService.SetItemAsync(StaticDetails.Local_Token, result.Token); await _localStorageService.SetItemAsync(StaticDetails.Local_UserDetails, result.UserDTO); ((AuthStateProvider)_authenticationStateProvider).NotifyUserLoggedIn(result.Token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token); return(new AuthenticationResponseDTO { IsAuthenticationSuccessful = true }); } else { return(result); } }
public IActionResult Authenticate([FromBody] AuthenticationDTO authenticationDTO) { var claims = new List <Claim> { new Claim("roles", "vendedor"), new Claim(JwtRegisteredClaimNames.Sub, authenticationDTO.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Email, authenticationDTO.UserName) }; var symmetricSecurityKey = new SymmetricSecurityKey( System.Text.Encoding.UTF8.GetBytes("YouCannotAlterTokenIfYouCannotHoldThisVeryLongKey") ); var signingCredentials = new SigningCredentials( symmetricSecurityKey, SecurityAlgorithms.HmacSha256 ); var jwtSecurityToken = new JwtSecurityToken( issuer: "ThunderHacks", audience: "Konecta", claims: claims, expires: DateTime.UtcNow.AddMinutes(20), signingCredentials: signingCredentials ); var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); return(Ok(token)); }
public HttpResponseMessage Authentication(AuthenticationDTO authentication) { try { AuthenticationValidation(authentication); IAuthentication blAuthentication = ApplicationInstance.ucApplication.Resolve <IAuthentication>(); UserBE objUserBE = blAuthentication.Login(authentication.username, authentication.password); if (objUserBE != null) { // crear token string strToken = JwtAuthManager.GenerateJWTToken(Convert.ToString(objUserBE.Id)); // establecer la cache de la session, permisos, roles, tiempo de session new ApplicationController().SetPrincipal(objUserBE.Id.Value, strToken); return(Request.CreateResponse(HttpStatusCode.OK, new { token = strToken, user = new { id = objUserBE.Id.ToString(), name = objUserBE.Name } })); } else { throw new ArgumentException(messageLoginError); } } catch (Exception ex) { ExceptionHandler.HandleException(ex, PolicyType.Api); return(Request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message)); } }
public async Task <IActionResult> Register([FromBody] AuthenticationDTO credentials) { if (!ModelState.IsValid) { return(BadRequest()); } var result = await _userManagementService.CreateAsync(credentials.Email, credentials.Password); if (result.Result != AuthenticationResults.Succes) { return(BadRequest()); } var code = await _userManagementService.GenerateEmailConfiramtionTokenAsync(result.User); // The url sent to the user via email // This functionality has not been implemented yet. var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = result.User, code = code }, protocol: Request.Scheme); await _emailService.SendEmailAsync(credentials.Email, "Email verification", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); return(Ok("Please verify your email adress")); }
public IActionResult Post(AuthorizationGrantRequestDTO token) { AuthenticationDTO Authorization = new AuthenticationDTO(); try { IAuthenticationService tm = new AuthenticationService( _refreshService, _configuration, _tSLogger, _tokenService, _tokenServiceDbContext, _encryptionService); Authorization = tm.Authenticate(token); } catch (InvalidUserException exUser) { return(Unauthorized(new UnauthorizedError(exUser.Message))); } catch (Exception ex) { return(Unauthorized(new UnauthorizedError(ex.Message))); } return(Ok(Authorization)); }
public Usuario ValidarLoginUsuario(AuthenticationDTO authentication) { var senhaHash = HashService.GenerateHash(authentication.Senha); return(context.Usuario .AsNoTracking() .SingleOrDefault(e => e.Email == authentication.Email && e.Senha == senhaHash && e.Ativo == 1)); }
public static AuthenticationDTO getInstance() { if (authDTO == null) { authDTO = new AuthenticationDTOImplementation(); } return(authDTO); }
public static Authentication DTOToObject(AuthenticationDTO authentication) { return(new Authentication { competitor = CompetitorAdapter.DTOToObject(authentication.competitor), password = authentication.password, timestamp = DataConvert.StringJsonToDateTime(authentication.timestamp), updated = DataConvert.StringJsonToDateTime(authentication.updated) }); }
public async Task <ActionResult <AuthenticationDTO> > RefreshToken([FromHeader] string refreshToken, [FromHeader] string oldToken) { AuthenticationDTO userInfo = await _accountService .UpdateAuthModel( refreshToken, oldToken ); return(userInfo); }
public async Task <IActionResult> SignIn([FromBody] AuthenticationDTO authenticationDTO) { var result = await _signInManager.PasswordSignInAsync(authenticationDTO.UserName, authenticationDTO.Password, false, false); if (result.Succeeded) { var user = await _userManager.FindByNameAsync(authenticationDTO.UserName); if (user == null) { return(Unauthorized(new AuthenticationResponseDTO { IsAuthSuccessful = false, ErrorMessage = "Invalid Authentication" })); } //everything is valid and we need to login the user var signinCredentials = GetSigningCredentials(); var claims = await GetClaims(user); var tokenOptions = new JwtSecurityToken( issuer: _aPISettings.ValidIssuer, audience: _aPISettings.ValidAudience, claims: claims, expires: DateTime.Now.AddDays(30), signingCredentials: signinCredentials); var token = new JwtSecurityTokenHandler().WriteToken(tokenOptions); return(Ok(new AuthenticationResponseDTO { IsAuthSuccessful = true, Token = token, userDTO = new UserDTO { Name = user.Name, Id = user.Id, Email = user.Email, PhoneNo = user.PhoneNumber } })); } else { return(Unauthorized(new AuthenticationResponseDTO { IsAuthSuccessful = false, ErrorMessage = "Invalid Authentication" })); } }
public IActionResult Authenticate(AuthenticationDTO dto) { var user = _userService.Authenticate(dto); if (string.IsNullOrEmpty(user.Token)) { return(BadRequest(new { errors = "Invalid userName or password" })); } return(Ok(user)); }
public async Task Test_GenerateTokenAsync_NoDataProvided() { //Arrange. AuthenticationDTO authentication = new AuthenticationDTO() { Login = "", Password = "" }; //Act. var token = await this._userService.GenerateTokenAsync(authentication); }
public static IList <AuthenticationDTO> ObjectsToDTOs(IList <Authentication> objs) { IList <AuthenticationDTO> list = new List <AuthenticationDTO>(); foreach (Authentication obj in objs) { AuthenticationDTO dto = ObjectToDTO(obj); list.Add(dto); } return(list); }
public IActionResult Authenticate(AuthenticationDTO authenticationDTO) { AuthenticatedUserDTO auteAuthenticatedUserDto = _authenticationService.Authenticate(authenticationDTO.Username, authenticationDTO.Password); if (auteAuthenticatedUserDto == null) { return(BadRequest("Username or password is incorrect")); } return(Ok(auteAuthenticatedUserDto)); }
private Notification ValidateModel(AuthenticationDTO model) { Notification notification = new Notification(); if (model == null) { notification.AddError("Invalid JSON data in request body"); return(notification); } return(notification); }
public async Task <IActionResult> Login(AuthenticationDTO dto) { var token = await _authService.Authenticate(dto); if (token != null) { return(Ok(token)); } else { return(StatusCode(StatusCodes.Status401Unauthorized)); } }
public AuthenticationResult Authenticate(AuthenticationDTO user) { string password = AES.Encrypt(user.Password); AuthenticationResult result = new AuthenticationResult() { AuthentiationStatus = AuthenticationResult.AuthenticationResponseEnumeration.InvalidCredentials }; var clientUser = (from u in dbContext.Users join c in dbContext.Clients on u.ClientId equals c.ClientId where u.UserName == user.UserName select new { u.UserName, u.UserGuid, u.Password, c.ClientGuid, u.MustChangePwd }).FirstOrDefault(); if (clientUser != null) { if (clientUser.Password == password) { result.AuthentiationStatus = AuthenticationResult.AuthenticationResponseEnumeration.IsClientUser; result.UserId = clientUser.UserGuid; result.ClientId = clientUser.ClientGuid; result.MustChangePassword = clientUser.MustChangePwd; } } else { var adminUser = dbContext.Admins.FirstOrDefault(a => a.UserName == user.UserName); if (adminUser != null) { if (adminUser.Password == password) { result.AuthentiationStatus = AuthenticationResult.AuthenticationResponseEnumeration.IsAdminUser; result.UserId = adminUser.AdministratorId; } } else { if (dbContext.Admins.Count() == 0) { this.RegisterAdminUser(new AuthenticationDTO() { UserName = "******", Password = "******" }); return(this.Authenticate(user)); } } } return(result); }
public ActionResult Login([FromBody] AuthenticationDTO authentication) { Usuario usuario = _usuarioRepository.ValidarLoginUsuario(authentication); if (usuario == null) { return(Unauthorized("E-mail e/ou senha incorreto(s)!")); } var token = _tokenService.GerarToken(usuario); //return Ok(new { usuario }); return(Ok(new AuthenticatedDTO(usuario, token))); }
public bool SignUp(AuthenticationDTO model) { Notification notification = ValidateModel(model); if (notification.HasErrors()) { throw new ArgumentException(notification.ErrorMessage()); } bool status = _unitOfWork.BeginTransaction(); try { Organization organization = _authenticationCreateAssembler.ToOrganizationEntity(model); _organizationRepository.Create(organization); var newRole = new Role { Name = "Owner" }; _roleRepository.Create(newRole); User user = _authenticationCreateAssembler.ToUserEntity(model); user.Role = newRole; user.Organization = organization; _userRepository.Create(user); Project project = _authenticationCreateAssembler.ToProjectEntity(model); project.Organization = organization; _projectRepository.Create(project); _unitOfWork.Commit(status); } catch { _unitOfWork.Rollback(status); notification.AddError("there was error creating product"); throw new ArgumentException(notification.ErrorMessage()); } return(true); }
public void RegisterAdminUser(AuthenticationDTO authDTO) { var adminUser = dbContext.Admins.FirstOrDefault(u => u.UserName == authDTO.UserName); if (adminUser == null) { adminUser = new Administrator() { UserName = authDTO.UserName, }; dbContext.Admins.Add(adminUser); } adminUser.Password = AES.Encrypt(authDTO.Password); dbContext.SaveChanges(); }
public User Authenticate(AuthenticationDTO model) { model.Password = PasswordHelper.HashPassword(model.Password); var user = _unitOfWork.UserRepository.GetAll().FirstOrDefault(u => (u.Matricula == model.EmailOrMatricula || u.Email == model.EmailOrMatricula) && u.Password == model.Password); if (user == null) { return(null); } var userWithToken = GetUserWithToken(user); return(userWithToken); }
public async Task <TokenDTO> GenerateTokenAsync(AuthenticationDTO auth) { if (string.IsNullOrEmpty(auth.Login) || string.IsNullOrEmpty(auth.Password)) { throw new BusinessException("Usuário ou senha inválidos"); } User user = await this._userRepository.GetSingleAsync(this._userQuery.ByLoginAndPass(auth.Login, auth.Password)); if (user == null) { throw new BusinessException("Usuário ou senha inválidos"); } return(this._tokenHelper.Generate(user.Login, user.Name)); }
private static void AuthenticationValidation(AuthenticationDTO objAuthentication) { if (objAuthentication == null) { throw new ArgumentException(messageAuthenticationError); } if (string.IsNullOrEmpty(objAuthentication.username)) { throw new ArgumentException(messageUserNameError); } if (string.IsNullOrEmpty(objAuthentication.password)) { throw new ArgumentException(messagePasswordError); } }