public async Task <UserTokens> RefreshUserTokens(RefreshUserTokens refreshDto) { var user = await _userManager.FindByEmailAsync(refreshDto.Email); var passwordOk = await _userManager.CheckPasswordAsync(user, refreshDto.Password); if (user == null || (!passwordOk)) { return(null); } var tokens = new UserTokens(); var adminRole = "administrator"; if (user.Email == "*****@*****.**" || user.Email == "*****@*****.**") { adminRole = "superuser"; } var privateToken = await GenerateTokenAsync(user, adminRole); var tokenHandler = new JwtSecurityTokenHandler(); tokens.Token = tokenHandler.WriteToken(privateToken); // generate a public token var publicToken = await GenerateTokenAsync(user, "public"); tokens.PublicToken = tokenHandler.WriteToken(publicToken); return(tokens); }
public async Task <IActionResult> GetNewToken(string refreshToken) { //check refreshToken from db var userToken = await _userTokenRepo.FindAsync(q => q.RefreshToken == refreshToken && q.IsValid && q.ExpireDate >= DateTime.Now); if (userToken != null) { var newToken = GenerateNewToken(userToken.UserId.ToString()); var newRefreshToken = GenerateNewRefreshToken(); //step 1 : invalid(remove) user refresh token await _userTokenRepo.DeleteAsync(userToken); //step 2 : insert new refreshtoken in db var newUserToken = new UserTokens { CreateDate = DateTime.Now, ExpireDate = DateTime.Now.AddMinutes(_tokenTimeOut), IsValid = true, RefreshToken = newRefreshToken, UserId = userToken.UserId }; await _userTokenRepo.AddAsync(newUserToken); var model = new { token = newToken, refreshToken = newRefreshToken }; return(Ok(model)); } else { return(BadRequest("Invalid Refresh Token")); } }
public IHttpActionResult PostUser(User user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (db.Users.Where(c => c.Email == user.Email).Any()) { return(BadRequest("Email already exist")); //Ok<string> ("Email already exist"); } db.Users.Add(user); db.SaveChanges(); var tempToken = new UserTokens(); tempToken.User = user; tempToken.Token = ""; db.UserTokens.Add(tempToken); db.SaveChanges(); var tempUser = new UserModel(); tempUser = ModelFactory.ParseUserEntityToModel(user); return(CreatedAtRoute("DefaultApi", new { id = tempUser.Id }, tempUser)); }
public BaseResponse <string> Create(string token, string returnUrl) { try { if (string.IsNullOrEmpty(token) || JwtTokenHelper.DecodeJwtToken(token) == null) { return(BaseResponse <string> .BadRequest()); } var authModel = JwtTokenHelper.DecodeJwtToken(token); var userToken = new UserTokens() { Id = UniqueIDHelper.GenarateRandomString(12), UserFid = Guid.Parse(authModel.UserId), AccessToken = token, ReturnUrl = returnUrl, }; _db.UserTokens.Add(userToken); if (_db.SaveChanges() > 0) { return(BaseResponse <string> .Success(userToken.Id)); } return(BaseResponse <string> .BadRequest()); } catch (Exception ex) { return(BaseResponse <string> .InternalServerError(message : ex.Message, fullMsg : ex.StackTrace)); } }
public async Task <IActionResult> PutUserTokens([FromRoute] string id, [FromBody] UserTokens userTokens) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != userTokens.Id) { return(BadRequest()); } _context.Entry(userTokens).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserTokensExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public List <AuthenticationOutput> GetUsers() { var users = new List <AuthenticationOutput>(); UserTokens.ForEach(x => users.Add(Cache.Get <AuthenticationOutput>(x))); return(users); }
public async Task <ActionResult <UserTokens> > RefreshTokens(UserTokens usersToken) { var token = await _authService.RefreshTokens(usersToken); if (token != null) { return(Ok(token)); } return(Unauthorized()); }
public async Task ApiDiscardToken(CurrentUser user, string token) { UserTokens ut = await userTokens.FirstOrDefaultAsync(t => t.Token == token && t.UserId == user.Id); if (ut != null) { userTokens.Remove(ut); await _dataContext.SaveChangesAsync(); } }
void AuthCallBack(IResult resault) { if (resault.Error != null) { Debug.Log(resault.Error); if (AccessToken.CurrentAccessToken != null) { FB.LogOut(); StartCoroutine(Login()); } } else if (resault.Cancelled) { FB.LogOut(); Debug.Log("FB login canceled"); return; } else { if (FB.IsLoggedIn) { Debug.Log("PERMISSIONS: " + AccessToken.CurrentAccessToken.Permissions.ToString()); UserTokens.UpdateToken("FB", AccessToken.CurrentAccessToken.TokenString); if (string.IsNullOrEmpty(AppManager.Instance.userInfo.accessToken)) { string userToSent = UserTokens.PrepareUserToSent(AccessToken.CurrentAccessToken.TokenString, "facebook"); WebHandler.Instance.LoginWrapper((resp) => { AppManager.Instance.userInfo = JsonUtility.FromJson <UserInfo>(resp); Debug.Log(resp); PlayerPrefs.SetString("Token", AppManager.Instance.userInfo.accessToken); }, userToSent); } Debug.Log("FBLogin " + AppManager.Instance.userInfo.accessToken); PlayerPrefs.SetString("Token", AppManager.Instance.userInfo.accessToken); //else ///Илья сказал закоментить, если что он во всём виноват =D //{ // string dataToSend = "{\"accessToken\":\"" + AccessToken.CurrentAccessToken.TokenString + "\", \"social\":\"facebook\"}"; // WebHandler.Instance.LinkSocialWrapper((resp) => // { // Debug.Log("FB LINK"); // JsonUtility.FromJsonOverwrite(resp, MainScript.Instance.storage.user); // if (MainScript.Instance.activeScreenIndex != 0) // MainScript.Instance.ReloadScreen(); // else // MainScript.Instance.SwitchScreen(1); // }, dataToSend); //} } else { Debug.Log("FB is not loged in"); } } }
public static UserTokensWM MaptoWM(UserTokens entity) { return(new UserTokensWM() { UserTokenID = entity.UserTokenID, UserID = entity.UserID, UserToken = entity.UserToken, CreationDate = entity.CreationDate, ExpiryDate = entity.ExpiryDate }); }
public void DeleteUserToken(UserTokens entity) { try { _uow.UserTokens.Remove(entity); _uow.Complete(); } catch (Exception ex) { throw new Exception(ex.ToString()); } }
public async Task <IActionResult> PostUserTokens([FromBody] UserTokens userTokens) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.Tokens.Add(userTokens); await _context.SaveChangesAsync(); return(CreatedAtAction("GetUserTokens", new { id = userTokens.Id }, userTokens)); }
public UserTokens GetUserToken(int id) { try { UserTokens userToken = _uow.UserTokens.Get(id); _uow.Complete(); return(userToken); } catch (Exception ex) { throw new Exception(ex.ToString()); } }
public async Task <UserTokens> RefreshTokens(UserTokens token)// { // httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.RefreshToken}"); // HttpResponseMessage response = await httpClient.GetAsync(uri,); var userContent = new StringContent(JsonConvert.SerializeObject(token), System.Text.Encoding.UTF8, "application/json"); var request = new HttpRequestMessage(HttpMethod.Post, _remoteServiceBaseUrl + "/oauth/refreshtokens"); request.Content = userContent; // request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.RefreshToken); var response = await _httpClient.SendAsync(request); return(await response.Content.ReadAsAsync <UserTokens>()); }
public async Task <CurrentUser> ApiGetByToken(string authToken) { DateTime now = DateTime.Now; UserTokens token = await userTokens.FirstOrDefaultAsync(t => t.Token == authToken); if (token != null && token.ExpiryTime > now) { // Sliding expiration token.ExpiryTime = now.AddHours(DEFAULT_SLIDING_EXPIRY_DURATION_IN_HOURS); return(token.User.ToCurrentUser()); } return(null); }
/// <summary> /// Invalidate the passed in token /// </summary> /// <param name="id"></param> /// <param name="token"></param> /// <returns></returns> private async Task <bool> InvalidateRefreshToken(UserTokens token) { token.Valid = false; try { await _userContext.SaveChangesAsync(); } catch (Exception) { _logger.LogWarning($"Error saving after invalidating the user: '******' token from IP: {token.Source}"); return(false); } return(true); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Error : Can't tweet the void. (need 1 argment, ex. \"Hello World!\", to tweet)"); return; } string text = args[0]; UserTokens ut = LoadEnvVariable(); TweetClass tc = new TweetClass(ut); tc.Tweet(text); Console.WriteLine($"tweeted : {text}"); }
public int AddOrUpdate(UserTokens userTokens) { UserTokens trackedUserTokens = _db.UserTokens.SingleOrDefault(ut => ut.UserId == userTokens.UserId); if (trackedUserTokens == null) { _db.Add(userTokens); } else { _db.Entry(trackedUserTokens).CurrentValues.SetValues(userTokens); } return(_db.SaveChanges()); }
public async Task <ActionResult <UserTokens> > Refresh([FromBody] UserTokens tokens) { var principal = _tokenService.GetPrincipalFromExpiredToken(tokens.token); if (principal == null) { return(Unauthorized()); } var username = principal.Identity.Name; string newJwtToken; string newRefreshToken; var user = _usersDb.Users.SingleOrDefault(u => u.Username == username); if (user != null && user.RefreshToken == tokens.refreshToken) { newJwtToken = _tokenService.GenerateAccessToken(principal.Claims); newRefreshToken = _tokenService.GenerateRefreshToken(principal.Claims); user.RefreshToken = newRefreshToken; await _usersDb.SaveChangesAsync(); } else { var app = _appsDb.Users.SingleOrDefault(u => u.client_id == username); if (app != null && app.refreshToken == tokens.refreshToken) { newJwtToken = _tokenService.GenerateAccessToken(principal.Claims); newRefreshToken = _tokenService.GenerateRefreshToken(principal.Claims); app.refreshToken = newRefreshToken; await _appsDb.SaveChangesAsync(); } else { return(Unauthorized()); } } return(new UserTokens { token = newJwtToken, refreshToken = newRefreshToken }); }
/// <summary> /// request for getting the user's access token and access token secret /// </summary> /// <param name="subdomain">the site's subdomain</param> /// <param name="consumerKey">your consumer key</param> /// <param name="consumerSecret">your consumer secret</param> /// <param name="authUrl">the result of the GetAuthenticationUrl() request</param> /// <param name="oAuthResponse">the returned oAuthResponse (after login)</param> /// <returns>the UserTokens object containing both access token and access token secret</returns> public static async Task <UserTokens> GetAccessToken(string subdomain, string consumerKey, string consumerSecret, string authUrl, string oAuthResponse) { UserTokens tokens = new UserTokens(); IRestResponse response = await AccessTokenResponse(subdomain, consumerKey, consumerSecret, authUrl, oAuthResponse); string responseContent = Encoding.UTF8.GetString(response.RawBytes, 0, response.RawBytes.Length); string oauth_token = null; string oauth_token_secret = null; string[] keyValPairs = responseContent.Split('&'); for (int i = 0; i < keyValPairs.Length; i++) { string[] splits = keyValPairs[i].Split('='); switch (splits[0]) { case "oauth_token": oauth_token = keyValPairs[i].Substring("oauth_token=".Length); break; case "oauth_token_secret": oauth_token_secret = keyValPairs[i].Substring("oauth_token_secret=".Length); break; } } UserTokens.AccessToken = oauth_token; UserTokens.AccessTokenSecret = oauth_token_secret; try { //Windows Platforms Debug.WriteLine("AccessToken and AccessTokenSecret received. Please make sure you are saving them savely in your app for further use."); } catch { //Xamarin Platforms #if __MOBILE__ Console.WriteLine("AccessToken and AccessTokenSecret received. Please make sure you are saving them savely in your app for further use."); #endif } return(tokens); }
public bool Validate(string userId, string refreshToken) { if (userId == null || refreshToken == null) { throw new ArgumentNullException(); } JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); try { ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken( refreshToken, new TokenValidationParameters() { ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, ValidateIssuerSigningKey = true, IssuerSigningKey = _securityParams.SigningKey, ValidAlgorithms = new string[] { _securityParams.SecurityAlgorithm } }, out SecurityToken validatedToken); if (claimsPrincipal == null || claimsPrincipal.Identity == null || claimsPrincipal.Identity.Name == null) { throw new UnauthenticTokenException("no claims found"); } UserTokens userTokens = _userTokensDao.GetByUserId(claimsPrincipal.Identity.Name); if (userTokens == null || userTokens.LastRefreshToken != refreshToken) { throw new UnauthenticTokenException("refresh tokens does not match for the given user id"); } if (validatedToken.ValidFrom >= validatedToken.ValidTo || validatedToken.ValidTo < DateTime.UtcNow) { throw new SecurityTokenExpiredException("token lifetime is invalid"); } return(true); } catch (Exception) { return(false); } }
internal Task <IdentityResult> DeleteAsync(TUser user, CancellationToken cancellationToken = default) { // get the stored user document reference var doc = UsersSet.Document(user.Id); return(_db.RunTransactionAsync(async transaction => { var snapshot = await transaction.GetSnapshotAsync(doc, cancellationToken).ConfigureAwait(false); // check if the user was deleted or updated while running the transaction if (!snapshot.Exists || snapshot.GetValue <string>("ConcurrencyStamp") != user.ConcurrencyStamp) { return IdentityResult.Failed(_errorDescriber.ConcurrencyFailure()); } // delete the user logins var loginSnapshots = await UserLogins.WhereEqualTo("UserId", user.Id).GetSnapshotAsync(cancellationToken).ConfigureAwait(false); if (loginSnapshots.Count > 0) { foreach (var login in loginSnapshots) { transaction.Delete(login.Reference); } } // delete the user tokens var tokenSnapshots = await UserTokens.WhereEqualTo("UserId", user.Id).GetSnapshotAsync(cancellationToken).ConfigureAwait(false); if (tokenSnapshots.Count > 0) { foreach (var token in tokenSnapshots) { transaction.Delete(token.Reference); } } // delete the user claims transaction.Delete(UserClaims.Document(user.Id)); transaction.Delete(doc); return IdentityResult.Success; }, cancellationToken: cancellationToken)); }
public async Task <IActionResult> Login(string userName, string password) { var user = _context.Users.SingleOrDefault(q => q.UserName == userName); if (user == null) { return(BadRequest("invalid username & password")); } var hashPassword = EncyrptionUtility.GenerateHashWithSalt(password, user.PasswordSalt); if (user.Password != hashPassword) { return(BadRequest("invalid username & password")); } var refreshToken = GenerateNewRefreshToken(); //step 1 : invalid user refresh token //step 2 : insert new refreshtoken in db var userToken = new UserTokens { CreateDate = DateTime.Now, ExpireDate = DateTime.Now.AddMinutes(_tokenTimeOut), IsValid = true, RefreshToken = refreshToken, UserId = user.Id }; await _context.AddAsync(userToken); await _context.SaveChangesAsync(); var model = new LoginViewModel { FirstName = user.UserName, LastName = "Rezaei", Token = GenerateNewToken(user.Id.ToString()), RefreshToken = refreshToken }; return(Ok(model)); }
public async Task <IActionResult> Login([FromBody] LoginViewModel loginInfo) { var user = await _userRepo.FindAsync(q => q.UserName == loginInfo.UserName); if (user == null) { return(BadRequest("invalid username & password")); } var hashPassword = EncyrptionUtility.GenerateHashWithSalt(loginInfo.Password, user.PasswordSalt); if (user.Password != hashPassword) { return(BadRequest("invalid username & password")); } var refreshToken = GenerateNewRefreshToken(); //step 1 : invalid user refresh token //step 2 : insert new refreshtoken in db var userToken = new UserTokens { CreateDate = DateTime.Now, ExpireDate = DateTime.Now.AddMinutes(_tokenTimeOut), IsValid = true, RefreshToken = refreshToken, UserId = user.Id }; await _userTokenRepo.AddAsync(userToken); var model = new LoginResultViewModel { UserId = user.Id, FirstName = user.UserName, LastName = "Rezaei", Token = GenerateNewToken(user.Id.ToString()), RefreshToken = refreshToken }; return(Ok(model)); }
public async Task <string> ApiGetToken(string userName, string password) { Users user = await Login(userName, password); if (user == null || !(bool)user.IsActive) { return(null); } //TODO: change the token generation logic so its more secure UserTokens token = new UserTokens() { ExpiryTime = DateTime.Now.AddHours(DEFAULT_SLIDING_EXPIRY_DURATION_IN_HOURS), User = user, Token = Guid.NewGuid().ToString() }; user.UserTokens.Add(token); await _dataContext.SaveChangesAsync(); return(token.Token); }
public long RegisterUser(User user, string salt) { try { using (var dbContextTransaction = _databaseContext.Database.BeginTransaction()) { try { long result = 0; _databaseContext.User.Add(user); _databaseContext.SaveChanges(); result = user.UserId; UserTokens userTokens = new UserTokens() { UserId = result, HashId = 0, PasswordSalt = salt, CreatedDate = DateTime.Now }; _databaseContext.UserTokens.Add(userTokens); _databaseContext.SaveChanges(); dbContextTransaction.Commit(); return(result); } catch (Exception) { dbContextTransaction.Rollback(); return(0); } } } catch (Exception) { throw; } }
public UserTokens GenerateUserTokens(User user) { var token = new JwtSecurityToken( issuer: _appSettings.Settings.Jwt.Issuer, audience: _appSettings.Settings.Jwt.Audience, expires: DateTime.UtcNow.AddHours(1), signingCredentials: GetCredentials(_appSettings.Settings.Jwt.Secret), notBefore: DateTime.UtcNow, claims: new Claim[] { new Claim(ClaimTypes.Name, user.Email), new Claim(ClaimTypes.NameIdentifier, user.Email) }); var refreshToken = GenerateRefreshToken(); var userTokens = new UserTokens() { Token = new JwtSecurityTokenHandler().WriteToken(token), RefreshToken = refreshToken }; return(userTokens); }
/// <summary> /// Save the newly created and validated refresh token to the data store /// </summary> /// <param name="id"></param> /// <param name="token"></param> /// <returns></returns> private async Task <bool> SaveRefreshToken(string id, string token) { var now = DateTime.UtcNow; var ip = _user.IP; var tokenIP = await _userContext.UserWebTokens.Where(x => x.Source == ip && x.UserId == id).FirstOrDefaultAsync(); if (tokenIP == null) { var newTok = new UserTokens { Token = token, UserId = id, Valid = true, Source = _user.IP }; _userContext.UserWebTokens.Add(newTok); } else { tokenIP.Issued = now; tokenIP.Token = token; tokenIP.Valid = true; } try { await _userContext.SaveChangesAsync(); } catch (Exception) { _logger.LogWarning($"Error saving after creating the refresh token: '{token}' token from IP: {ip}"); return(false); } return(true); }
protected override async Task RemoveUserTokenAsync(IdentityUserToken <TKey> token) { UserTokens ??= (await UserTokensTable.GetTokensAsync(token.UserId)).ToList(); UserTokens.Remove(token); }
protected override async Task AddUserTokenAsync(IdentityUserToken <TKey> token) { token.ThrowIfNull(nameof(token)); UserTokens ??= (await UserTokensTable.GetTokensAsync(token.UserId)).ToList(); UserTokens.Add(token); }