public async Task <IActionResult> RenewTokens([FromBody] AuthenticationTokens authenticationTokens) { int userId; try { userId = authenticationTokens.GetUserIdFromClaims(_configuration.GetSecretKey()); await _loggingService.SaveAuditLog($"Refreshing tokens for user with user id {userId}", AuditActionEnum.TokenRefresh); } catch (Exception) { return(BadRequest()); } var refreshToken = await RetrieveRefreshToken(authenticationTokens.RefreshToken, userId); if (refreshToken == null || !_authenticationService.IsRefreshTokenValid(refreshToken)) { return(BadRequest()); } var newTokens = await _authenticationService.GenerateTokens(userId); await _loggingService.SaveAuditLog($"Deleting old refresh token for user with user id {userId}", AuditActionEnum.Delete); await _authenticationRepository.DeleteToken(refreshToken); return(Ok(newTokens)); }
public async Task <Result <AuthenticationTokens> > GenerateAuthenticationTokensAsync(Customer client) { #region Access token generation Result <string> jwtCreationResult = await accessTokenService.GenerateTokenAsync(client); if (!jwtCreationResult.Succeeded) { return(Result <AuthenticationTokens> .Failure(jwtCreationResult.Errors)); } // retrieve access token string accessToken = jwtCreationResult.Response; #endregion #region Refresh token generation Result <string> refreshTokenGenerationResult = await refreshTokenService.GenerateTokenAsync(client); if (!refreshTokenGenerationResult.Succeeded) { return(Result <AuthenticationTokens> .Failure(refreshTokenGenerationResult.Errors)); } // retrieve refreshtoken to separate variable string refreshToken = refreshTokenGenerationResult.Response; #endregion var response = new AuthenticationTokens(accessToken, refreshToken); return(Result <AuthenticationTokens> .Success(response)); }
public AuthenticationTokens tokens() { var _tokens = new AuthenticationTokens() { ApplicationPassword = password, //"AxlI q7CQ 8JtR Us6I LHcK 6I0Y", UserName = username }; return(_tokens); }
public static bool IsTokenValid(this AuthenticationTokens tokenDb, string token) { var tokenActiveHours = (DateTime.Now - (tokenDb?.TokenDate ?? DateTime.Now.AddDays(-5))).TotalHours; if (!token.IsSet() || tokenDb == null || (tokenDb?.IsDeleted ?? true) || tokenActiveHours > Constants.AuthTokenValidHours) { return(false); } return(true); }
//--- Methods --- protected override async Task OnInitializedAsync() { // remove any previous authentication tokens await LocalStorage.RemoveItemAsync("Tokens"); // check if page is loaded with a authorization grant code (i.e. ?code=XYZ) var queryParameters = HttpUtility.ParseQueryString(new Uri(NavigationManager.Uri).Query); var code = queryParameters["code"]; if (!string.IsNullOrEmpty(code)) { // ensure the replay guard matches var state = queryParameters["state"]; if (!await VerifyReplayGuardAsync(state)) { // TODO: report login error to user throw new NotImplementedException("replay guard failed"); } // fetch the authorization token from Cognito Console.WriteLine($"Fetching authentication tokens for code grant: {code}"); var oauth2TokenResponse = await HttpClient.PostAsync($"{CognitoSettings.UserPoolUri}/oauth2/token", new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("grant_type", "authorization_code"), new KeyValuePair <string, string>("code", code), new KeyValuePair <string, string>("client_id", CognitoSettings.ClientId), new KeyValuePair <string, string>("redirect_uri", CognitoSettings.RedirectUri) })); if (oauth2TokenResponse.IsSuccessStatusCode) { // store authentication tokens in local storage var json = await oauth2TokenResponse.Content.ReadAsStringAsync(); Console.WriteLine($"Storing authentication tokens: {json}"); var authenticationTokens = AuthenticationTokens.FromJson(json); await LocalStorage.SetItemAsync("Tokens", authenticationTokens); } else { // TODO: report login error to user throw new NotImplementedException("unable to retreive authentication tokens"); } // navigate back to main page to connect to the websocket NavigationManager.NavigateTo("/"); } else { Console.WriteLine("No code grant to fetch!"); LoginUrl = CognitoSettings.GetLoginUrl("TBD"); } }
private void RemoveAuthToken() { string t = GetAuthToken(); AuthenticationTokens token = _dbAuthenticationTokens.FindByAuthToken(t); if (token != null) { token.IsDeleted = true; token.DateTimeDeleted = DateTime.Now; _dbAuthenticationTokens.Edit(token); } }
public IHttpActionResult Login([FromBody] VMLogin model) { Users user = FindUser(model.Username, model.Password); if (user == null) { return(NotFound()); } if (!user.Active) { if (user.ActivationCode == null) { return(StatusCode(HttpStatusCode.Unauthorized)); } else { return(StatusCode(HttpStatusCode.Ambiguous)); } } _dbAuthenticationTokens.DeactivateByDeviceToken(model.DeviceToken); string generated = Guid.NewGuid().ToString(); AuthenticationTokens authenticationToken = new AuthenticationTokens { UserID = user.UserID, DateTimeCreated = DateTime.Now, DeviceToken = model.DeviceToken, AuthenticationToken = generated, Info_Version_Release = model.InfoVersionRelease, Info_Device = model.InfoDevice, Info_Model = model.InfoModel, Info_Product = model.InfoProduct, Info_Brand = model.InfoBrand, Info_Manufacturer = model.InfoManufacturer, Android_SerialOrID = model.AndroidSerialOrID }; _dbAuthenticationTokens.Add(authenticationToken); return(Ok(new VMAuthentication { UserID = user.UserID, AuthToken = generated, FirstName = user.FirstName, LastName = user.LastName, Username = model.Username, Email = user.Email, ProfilePhoto = user.ProfilePhoto })); }
private async Task <AuthenticationTokens> GetAuthenticationTokens() { // check if any authentication tokens are stored var authenticationTokens = await LoadTokensAsync(); if (authenticationTokens == null) { LogInfo($"No authentication tokens found"); return(null); } // check if tokens will expire in 5 minutes or less var authenticationTokenExpiration = DateTimeOffset.FromUnixTimeSeconds(authenticationTokens.Expiration); var authenticationTokenTtl = authenticationTokenExpiration - DateTimeOffset.UtcNow; if (authenticationTokenTtl < TimeSpan.FromSeconds(TOKEN_EXPIRATION_LIMIT_SECONDS)) { LogInfo($"Current authentication tokens has expired or expires soon: {authenticationTokenExpiration}"); // refresh authentication tokens LogInfo($"Refreshing authentication tokens for code grant: {authenticationTokens.IdToken}"); var oauth2TokenResponse = await HttpClient.PostAsync($"{CognitoSettings.UserPoolUri}/oauth2/token", new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("grant_type", "refresh_token"), new KeyValuePair <string, string>("client_id", CognitoSettings.ClientId), new KeyValuePair <string, string>("refresh_token", authenticationTokens.RefreshToken) })); if (!oauth2TokenResponse.IsSuccessStatusCode) { LogInfo("Authentication tokens refresh failed"); await ClearAuthenticationTokens(); return(null); } // store authentication tokens in local storage var json = await oauth2TokenResponse.Content.ReadAsStringAsync(); LogInfo($"Storing authentication tokens: {json}"); var refreshAuthenticationTokens = AuthenticationTokens.FromJson(json); authenticationTokens.IdToken = refreshAuthenticationTokens.IdToken; authenticationTokens.AccessToken = refreshAuthenticationTokens.AccessToken; authenticationTokens.Expiration = refreshAuthenticationTokens.Expiration; await SaveTokensAsync(authenticationTokens); } else { LogInfo($"Current authentication tokens valid until: {authenticationTokenExpiration}"); } return(authenticationTokens); }
public void Get_user_id_from_jwt_token_claims(string token, int expectedUserId) { var key = "qwertyuiopasdfghjklzxcvbnm123456lsh40897fsljlj4324ljk234k3jfsdfsdfsdfd45h34k5hg345lk3hg34jklg345kjhg345lkjh3g4534512312313dffsdf"; var authenticationTokens = new AuthenticationTokens { AccessToken = token, RefreshToken = "something" }; var actualUserId = authenticationTokens.GetUserIdFromClaims(key); Assert.Equal(expectedUserId, actualUserId); }
public IHttpActionResult Login([FromBody] LoginViewModel model) { if ((!model?.Username.IsSet() ?? true) || (!model?.Password.IsSet() ?? true)) { return(BadRequest("Username and password are not provided.")); } var user = _db.Users.FirstOrDefault(u => u.Username.Equals(model.Username)); if (user == null) { return(BadRequest($"Username or password are not correct.")); } var hash = Cryptography.GenerateHash(user.PasswordSalt, model.Password); if (!user.PasswordHash.Equals(hash)) { return(BadRequest($"Username or password are not correct.")); } var userAuthTokens = _db.AuthenticationTokens.Where(at => at.UserId == user.Id && !at.IsDeleted).ToList(); var newAuthToken = new AuthenticationTokens { DeviceId = model.DeviceId, Token = Guid.NewGuid().ToString(), TokenDate = DateTime.Now, UserId = user.Id, IsDeleted = false }; try { foreach (var item in userAuthTokens) { item.IsDeleted = true; } _db.AuthenticationTokens.Add(newAuthToken); _db.SaveChanges(); } catch (Exception) { return(BadRequest("An error ocured while trying to login to Wishlist, please try again later.")); } return(Ok(new { UserId = newAuthToken.UserId, Username = user.Username, AuthToken = newAuthToken.Token })); }
public async Task <AuthenticationTokens> GenerateTokens(int userId) { var tokenHandler = new JwtSecurityTokenHandler(); var accessToken = tokenHandler.CreateToken(SetUpToken(userId)); var refreshToken = RefreshTokenHelper.Generate(userId); await _authenticationRepository.CreateToken(refreshToken); var authenticationTokens = new AuthenticationTokens { AccessToken = tokenHandler.WriteToken(accessToken), RefreshToken = refreshToken.Token }; return(authenticationTokens); }
public static int GetUserIdFromClaims(this AuthenticationTokens tokens, string key) { var tokenValidationParameters = GenerateTokenValidationParameters(key); var tokenHandler = new JwtSecurityTokenHandler(); var claims = tokenHandler.ValidateToken(tokens.AccessToken, tokenValidationParameters, out var validatedToken); if (!(validatedToken is JwtSecurityToken jwtSecurityToken) || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token"); } return(int.Parse(claims.Identity.Name)); }
private ApiResult <VMAuthentication> AddAuthToken(string deviceToken, Users user) { if (user == null) { return(ApiResult <VMAuthentication> .Error(1, Resource.IncorrectLoginCredentials)); } if (!user.Active) { return(ApiResult <VMAuthentication> .Error(1, Resource.ErrMsgUserAccountNotActive)); } List <AuthenticationTokens> tokensToDelete = _dbAuthenticationTokens.FindByDeviceToken(deviceToken).ToList(); foreach (var token in tokensToDelete) { token.IsDeleted = true; token.DateTimeDeleted = DateTime.Now; _dbAuthenticationTokens.Edit(token); } string generated = Guid.NewGuid().ToString(); AuthenticationTokens authenticationToken = new AuthenticationTokens { UserID = user.UserID, DateTimeCreated = DateTime.Now, DeviceToken = deviceToken, AuthenticationToken = generated, }; _dbAuthenticationTokens.Add(authenticationToken); return(ApiResult <VMAuthentication> .OK(new VMAuthentication { UserID = user.UserID, AuthToken = generated, FirstName = user.FirstName, LastName = user.LastName, Username = user.Username, Email = user.Email, ProfilePhoto = user.ProfilePhoto })); }
public void HandleQuickConnect(dynamic JsonData) { var techSocket = Socket_Main.SocketCollection.Find(sm => sm?.TechAccount?.UserID.ToLower() == JsonData?.UserID.ToLower()); if (techSocket == null || !techSocket?.AuthenticationTokens?.Contains(JsonData?.AuthenticationToken)) { JsonData.Status = "denied"; Send(Json.Encode(JsonData)); return; } ConnectionType = ConnectionTypes.ViewerApp; TechAccount = (Tech_Account)techSocket.TechAccount.Clone(); AuthenticationTokens.AddRange(techSocket.AuthenticationTokens); var customerSocket = SocketCollection.Find(rc => rc.ConnectionType == ConnectionTypes.ClientService && rc.ComputerName == JsonData.ComputerName); if (customerSocket == null) { JsonData.Status = "notfound"; Send(Json.Encode(JsonData)); return; } if (TechAccount.AccessLevel != Tech_Account.Access_Levels.Admin && !TechAccount.ComputerGroups.Contains(customerSocket.ComputerGroup)) { JsonData.Status = "unauthorized"; Send(Json.Encode(JsonData)); return; } if (customerSocket.Partner != null) { customerSocket.Partner.Close(); } customerSocket.Partner = this; this.Partner = customerSocket; var request = new { Type = "ConnectUnattended", ComputerName = customerSocket.ComputerName, AuthenticationToken = JsonData.AuthenticationToken }; customerSocket.Send(Json.Encode(request)); LogSession(); }
public async Task <HttpResponseMessage> Login([FromBody] UILogin model) { Users foundUser = await _db.Users.Where(x => x.Username == model.Username).FirstOrDefaultAsync(); if (foundUser == null) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not authorized!")); } string hash = PasswordHelper.GenerateHash(foundUser.PasswordSalt, model.Password); if (foundUser.PasswordHash != hash) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not authorized!")); } //deactivate previous tokens foreach (var item in _db.AuthenticationTokens.Where(x => x.UserID == foundUser.UserID).ToList()) { item.IsDeleted = true; } _db.SaveChanges(); AuthenticationTokens newToken = new AuthenticationTokens { DeviceID = model.DeviceID, IsDeleted = false, UserID = foundUser.UserID, TokenDate = DateTime.Now, Token = Guid.NewGuid().ToString() }; _db.AuthenticationTokens.Add(newToken); _db.SaveChanges(); LoginResultDTO loginResult = new LoginResultDTO { token = newToken, user = foundUser }; return(Request.CreateResponse(HttpStatusCode.OK, loginResult)); }
public IHttpActionResult GetAccess() { string t = GetAuthToken(); AuthenticationTokens authenticationToken = _dbAuthenticationTokens.FindByAuthToken(t, false); if (authenticationToken?.UserID == null) { return(Unauthorized()); } Users user = _dbUsers.FindByID(authenticationToken.UserID); return(Ok(new VMAuthentication { UserID = user.UserID, AuthToken = authenticationToken.AuthenticationToken, FirstName = user.FirstName, LastName = user.LastName, Username = user.Username, Email = user.Email, ProfilePhoto = user.ProfilePhoto })); }
private bool AuthenticateTech(dynamic JsonData) { try { if (!AuthenticationTokens.Contains(JsonData.AuthenticationToken)) { var response = new { Type = "Unauthorized", Reason = "You are unauthorized to perform this action." }; Send(Json.Encode(response)); return(false); } return(true); } catch (Exception ex) { Utilities.WriteToLog(ex); return(false); } }
public Task <AuthenticationToken> GetActiveByAccountIdAsync(int accountId) { return(Task.Run(() => AuthenticationTokens.FirstOrDefault(x => x.AccountId == accountId))); }
public Task CreateAsync(AuthenticationToken authenticationToken) { return(Task.Run(() => AuthenticationTokens.Add(authenticationToken))); }
public Task <AuthenticationToken> GetActiveAsync(string token, int accountId) { return(Task.Run(() => AuthenticationTokens.FirstOrDefault(x => x.AccountId == accountId && x.Token == token))); }
public void HandleTechMainLogin(dynamic JsonData) { try { if (BadLoginAttempts >= 3) { JsonData.Status = "temp ban"; Send(Json.Encode(JsonData)); return; } if (Config.Current.Demo_Mode && JsonData.UserID.ToLower() == "demo" && JsonData.Password == "tech") { var authToken = Guid.NewGuid().ToString().Replace("-", ""); AuthenticationTokens.Add(authToken); TechAccount = new Tech_Account() { UserID = "demo", FirstName = "Demo", LastName = "Tech", HashedPassword = Crypto.HashPassword(JsonData.Password), AccessLevel = Tech_Account.Access_Levels.Admin }; if (JsonData.RememberMe == true) { TechAccount.AuthenticationTokens.AddRange(AuthenticationTokens); } TechAccount.Save(); JsonData.Status = "ok"; JsonData.AuthenticationToken = authToken; Send(Json.Encode(JsonData)); return; } //else if (Config.Current.Active_Directory_Enabled) //{ // // TODO: AD authentication. //} else { if (!Directory.Exists(Utilities.App_Data + "Tech_Accounts")) { Directory.CreateDirectory(Utilities.App_Data + "Tech_Accounts"); } if (!File.Exists(Utilities.App_Data + "Tech_Accounts\\" + JsonData.UserID + ".json")) { BadLoginAttempts++; JsonData.Status = "invalid"; Send(Json.Encode(JsonData)); return; } Tech_Account account = Json.Decode <Tech_Account>(File.ReadAllText(Utilities.App_Data + "Tech_Accounts\\" + JsonData.UserID + ".json")); while (account.AuthenticationTokens.Count > 10) { account.AuthenticationTokens.RemoveAt(0); } if (account.BadLoginAttempts >= 3) { if (DateTime.Now - account.LastBadLogin > TimeSpan.FromMinutes(10)) { BadLoginAttempts = 0; } else { JsonData.Status = "locked"; Send(Json.Encode(JsonData)); return; } } if (String.IsNullOrEmpty(JsonData.Password)) { BadLoginAttempts++; account.BadLoginAttempts++; account.LastBadLogin = DateTime.Now; account.Save(); JsonData.Status = "invalid"; Send(Json.Encode(JsonData)); return; } if (JsonData.Password == account.TempPassword) { if (String.IsNullOrEmpty(JsonData.NewPassword)) { JsonData.Status = "new required"; Send(Json.Encode(JsonData)); return; } else if (JsonData.NewPassword != JsonData.ConfirmNewPassword) { JsonData.Status = "password mismatch"; Send(Json.Encode(JsonData)); return; } else if (JsonData.NewPassword.Length < 8 || JsonData.NewPassword.Length > 20) { JsonData.Status = "password length"; Send(Json.Encode(JsonData)); return; } else { var authToken = Guid.NewGuid().ToString().Replace("-", ""); AuthenticationTokens.Add(authToken); account.TempPassword = ""; account.HashedPassword = Crypto.HashPassword(JsonData.ConfirmNewPassword); account.BadLoginAttempts = 0; if (JsonData.RememberMe == true) { account.AuthenticationTokens.Add(authToken); } account.Save(); if (SocketCollection.Exists(sock => sock?.TechAccount?.UserID == account.UserID)) { foreach (var login in SocketCollection.FindAll(sock => sock?.TechAccount?.UserID == account.UserID)) { var request = new { Type = "NewLogin" }; login.Send(Json.Encode(request)); login.Close(); } } TechAccount = account; JsonData.Status = "ok"; JsonData.Access = TechAccount.AccessLevel.ToString(); JsonData.AuthenticationToken = authToken; Send(Json.Encode(JsonData)); return; } } if (Crypto.VerifyHashedPassword(account.HashedPassword, JsonData.Password)) { var authToken = Guid.NewGuid().ToString().Replace("-", ""); AuthenticationTokens.Add(authToken); account.BadLoginAttempts = 0; account.TempPassword = ""; if (JsonData.RememberMe == true) { account.AuthenticationTokens.Add(authToken); } account.Save(); if (SocketCollection.Exists(sock => sock?.TechAccount?.UserID == account.UserID)) { foreach (var login in SocketCollection.FindAll(sock => sock?.TechAccount?.UserID == account.UserID)) { var request = new { Type = "NewLogin" }; login.Send(Json.Encode(request)); login.Close(); } } TechAccount = account; JsonData.Status = "ok"; JsonData.Access = TechAccount.AccessLevel.ToString(); JsonData.AuthenticationToken = authToken; Send(Json.Encode(JsonData)); return; } if (!String.IsNullOrEmpty(JsonData.AuthenticationToken)) { if (AuthenticationTokens.Contains(JsonData.AuthenticationToken) || account.AuthenticationTokens.Contains(JsonData.AuthenticationToken)) { var authToken = Guid.NewGuid().ToString().Replace("-", ""); account.AuthenticationTokens.Remove(JsonData.AuthenticationToken); AuthenticationTokens.Add(authToken); if (JsonData.RememberMe == true) { account.AuthenticationTokens.Add(authToken); } account.Save(); account.BadLoginAttempts = 0; account.TempPassword = ""; account.Save(); if (SocketCollection.Exists(sock => sock?.TechAccount?.UserID == account.UserID)) { foreach (var login in SocketCollection.FindAll(sock => sock?.TechAccount?.UserID == account.UserID)) { var request = new { Type = "NewLogin" }; login.Send(Json.Encode(request)); login.Close(); } } TechAccount = account; JsonData.Status = "ok"; JsonData.Access = TechAccount.AccessLevel.ToString(); JsonData.AuthenticationToken = authToken; Send(Json.Encode(JsonData)); } else { BadLoginAttempts++; JsonData.Status = "expired"; Send(Json.Encode(JsonData)); } return; } // Bad login attempt. BadLoginAttempts++; account.BadLoginAttempts++; account.LastBadLogin = DateTime.Now; account.Save(); JsonData.Status = "invalid"; Send(Json.Encode(JsonData)); return; } } catch (Exception ex) { Utilities.WriteToLog(ex); } }
public async Task <Result <AuthenticationTokens> > ExchangeAuthenticationTokensAsync(AuthenticationTokens tokens) { #region AccessToken Validation Result <ClaimsPrincipal> accessTokenValidationResult = await accessTokenService.ValidateTokenAsync(tokens.AccessToken); if (!accessTokenValidationResult.Succeeded) { return(Result <AuthenticationTokens> .Failure(accessTokenValidationResult.Errors)); } ClaimsPrincipal tokenClaims = accessTokenValidationResult.Response; #endregion #region RefreshToken Validation Result refTokenValResult = await refreshTokenService.ValidateTokenAsync(tokens.RefresthToken); if (!refTokenValResult.Succeeded) { return(Result <AuthenticationTokens> .Failure(refTokenValResult.Errors)); } #endregion #region Token Generation string clientId = accessTokenService.GetCustomerIdFromClaims(tokenClaims); Customer client = await clientManager.FindByIdAsync(clientId); return(await GenerateAuthenticationTokensAsync(client)); #endregion }