public async Task CreateAsync(AuthenticationTokenCreateContext context) { var clientid = context.Ticket.Identity.Name; var refreshTokenId = Guid.NewGuid().ToString("n"); var token = new RefreshToken() { Id = refreshTokenId, ClientId = clientid, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddSeconds(15) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); repo.Add(refreshTokenId, token); await Task.Delay(1); context.SetToken(refreshTokenId); //var allowedOrigins = context.OwinContext.Get<List<string>>("as:clientAllowedOrigins"); //context.OwinContext.Response.Headers.Add( // "Access-Control-Allow-Origin", // allowedOrigins.Select(x => x.ToString()).ToArray() // //new[] { "*" } // ); //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { var clientid = context.Ticket.Properties.Dictionary["as:client_id"]; if (string.IsNullOrEmpty(clientid)) { return; } var refreshTokenId = Guid.NewGuid().ToString("n"); var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime"); var token = new RefreshToken() { Id = HashMaker.GetHash(refreshTokenId), ClientId = clientid, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); var result = await authRepository.AddRefreshToken(token); if (result) { context.SetToken(refreshTokenId); } }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { if (!context.OwinContext.Environment.ContainsKey(IS_REFREHTOKEN_EXPIRED_NAME) || (bool)context.OwinContext.Environment[IS_REFREHTOKEN_EXPIRED_NAME]) { bool result = false; var refreshTokenId = Guid.NewGuid().ToString("n"); var clientId = context.Ticket.Properties.Dictionary["audience"]; var refreshTokenLifetime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime") ?? "30"; var token = new RefreshToken() { Id = Utilities.GetHash(refreshTokenId), ClientId = clientId, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddDays(Double.Parse(refreshTokenLifetime)) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); using (IApplicationRepository rep = new ApplicationRepository()) { result = await rep.RefreshTokens.AddAsync(token); } if (result) { context.SetToken(refreshTokenId); } } }
public async Task<string> CreateRefreshTokenAsync(Token accessToken, Client client) { Logger.Debug("Creating refresh token"); int lifetime; if (client.RefreshTokenExpiration == TokenExpiration.Absolute) { Logger.Debug("Setting an absolute lifetime: " + client.AbsoluteRefreshTokenLifetime); lifetime = client.AbsoluteRefreshTokenLifetime; } else { Logger.Debug("Setting a sliding lifetime: " + client.SlidingRefreshTokenLifetime); lifetime = client.SlidingRefreshTokenLifetime; } var refreshToken = new RefreshToken { Handle = Guid.NewGuid().ToString("N"), ClientId = client.ClientId, CreationTime = DateTime.UtcNow, LifeTime = lifetime, AccessToken = accessToken }; await _store.StoreAsync(refreshToken.Handle, refreshToken); return refreshToken.Handle; }
public static void SaveRefreshToken(dynamic inputs) { try { RefreshToken rft = new RefreshToken(); rft.token = inputs.HashedToken; rft.username = inputs.Username; rft.client_id = inputs.ClientId; rft.expires_on = inputs.ExpiresUtc; rft.issued_on = inputs.IssuedUtc; rft.protected_ticket = inputs.ProtectedTicket; using (var ctx = new SMContext()) { ctx.RefreshTokens.Add(rft); ctx.SaveChanges(); } } catch (Exception ex) { BaseClass.logger.Error("Database Query SaveRefreshToken: ", ex); } }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { var clientId = context.Ticket.Properties.Dictionary["client_id"]; if (string.IsNullOrEmpty(clientId)) { return; } var refreshTokenId = Guid.NewGuid().ToString("n"); var token = new RefreshToken { Id = refreshTokenId, ClientId = clientId, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddHours( Convert.ToInt32(WebConfigurationManager.AppSettings["RefreshTokenExpiration"])) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); //TODO: store the token somewhere context.SetToken(refreshTokenId); }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { var refreshTokenId = Guid.NewGuid().ToString("n"); using (var ctx = new ApplicationDbContext()) { var token = new RefreshToken() { Id = Helper.GetHash(refreshTokenId), Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddDays(30) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); var result = await ctx.AddRefreshToken(token); if (result) { context.SetToken(refreshTokenId); } } }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { try { var clientid = context.Ticket.Properties.Dictionary["as:client_id"]; if (string.IsNullOrEmpty(clientid)) return; // Gera um ID unico para o RefreshToken var refreshTokenId = Guid.NewGuid().ToString("n"); // Pega o tempo de expiração (em minuto) do token do contexto do Owin var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime"); // Identifica o Browser var userAgent = HttpContext.Current.Request.UserAgent; var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } }; var factory = new BrowserCapabilitiesFactory(); factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser); var browser = userBrowser.Browser; var issuedUtc = DateTime.UtcNow; var expiresUtc = issuedUtc.AddMinutes(3); //issuedUtc.AddMonths(Convert.ToInt32(refreshTokenLifeTime)); // Define os dados do RefreshToken var token = new RefreshToken { Id = HashHelper.GetHash(refreshTokenId), ClientId = clientid, Browser = browser, Subject = context.Ticket.Identity.Name, IssuedUtc = issuedUtc, ExpiresUtc = expiresUtc }; // Define o IssuedUtc e o ExpiresUtc do ticket para determinar o quanto tempo o token vai ser válido context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; // Serializa o ticket para ser gravado na base de dados var ticketSerializer = new TicketSerializer(); token.ProtectedTicket = ticketSerializer.Serialize(context.Ticket); // Grava o ticket na base de dados var refreshTokenDomain = DependecyConfig.Container.GetInstance<IRefreshTokenDomain>(); var result = await refreshTokenDomain.CreateAsync(token); if (result) context.SetToken(refreshTokenId); } catch (Exception ex) { throw ex; } }
public async Task<bool> AddRefreshToken(RefreshToken token) { var existingToken = await _db.RefreshTokens.Where(r => r.Subject == token.Subject && r.ClientId == token.ClientId && r.DeviceId == token.DeviceId).FirstOrDefaultAsync(); if (existingToken != null) { await RemoveRefreshToken(existingToken); } _db.RefreshTokens.Add(token); return await _db.SaveChangesAsync() > 0; }
public async Task<string> UpdateRefreshTokenAsync(RefreshToken refreshToken, Client client) { Logger.Debug("Updating refresh token"); bool needsUpdate = false; string oldHandle = refreshToken.Handle; if (client.RefreshTokenUsage == TokenUsage.OneTimeOnly) { Logger.Debug("Token usage is one-time only. Generating new handle"); // generate new handle refreshToken.Handle = Guid.NewGuid().ToString("N"); needsUpdate = true; } if (client.RefreshTokenExpiration == TokenExpiration.Sliding) { Logger.Debug("Refresh token expiration is sliding - extending lifetime"); // make sure we don't exceed absolute exp // cap it at absolute exp var currentLifetime = refreshToken.CreationTime.GetLifetimeInSeconds(); Logger.Debug("Current lifetime: " + currentLifetime.ToString()); var newLifetime = currentLifetime + client.SlidingRefreshTokenLifetime; Logger.Debug("New lifetime: " + newLifetime.ToString()); if (newLifetime > client.AbsoluteRefreshTokenLifetime) { newLifetime = client.AbsoluteRefreshTokenLifetime; Logger.Debug("New lifetime exceeds absolute lifetime, capping it to " + newLifetime.ToString()); } refreshToken.LifeTime = newLifetime; needsUpdate = true; } if (needsUpdate) { // delete old one await _store.RemoveAsync(oldHandle); // create new one await _store.StoreAsync(refreshToken.Handle, refreshToken); Logger.Debug("Updated refresh token in store"); return refreshToken.Handle; } Logger.Debug("No updates to refresh token done"); return oldHandle; }
public Task<SearchResult<IPackageSearchMetadata>> RefreshSearchAsync (RefreshToken refreshToken, CancellationToken cancellationToken) { var items = Packages .Select (package => PackageSearchMetadataBuilder.FromIdentity (package).Build ()) .ToArray (); var results = SearchResult.FromItems (items); results.NextToken = new ContinuationToken { }; results.SourceSearchStatus = new Dictionary<string, LoadingStatus> { { "Test", LoadingStatus.Ready } }; return Task.FromResult (results); }
public async Task<bool> AddRefreshToken(RefreshToken token) { var existingToken = _ctx.RefreshTokens.Where(r => r.Subject == token.Subject && r.ClientId == token.ClientId).SingleOrDefault(); if (existingToken != null) { var result = await RemoveRefreshToken(existingToken); } _ctx.RefreshTokens.Add(token); return await _ctx.SaveChangesAsync() > 0; }
public RefreshTokenModel CreateViewModel(RefreshToken datamodel) { if (datamodel == null) { throw new ArgumentNullException("datamodel"); } return new RefreshTokenModel() { Id = datamodel.Id, ClientId = datamodel.ClientId, Subject = datamodel.Subject, ExpiresUtc = datamodel.ExpiresUtc, IssuedUtc = datamodel.IssuedUtc }; }
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context) { var authClient = context.OwinContext.Get<AuthClient>("authClient"); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { authClient.AllowedOrigin }); //TODO: get the refresh token var token = new RefreshToken(); if (token != null) { context.DeserializeTicket(token.ProtectedTicket); //TODO: remove token when used } }
public async Task<bool> AddRefreshToken(RefreshToken token) { var query = Query.And( Query<RefreshToken>.EQ(r => r.Subject, token.Subject), Query<RefreshToken>.EQ(r => r.ClientId, token.ClientId)); var existingToken = mongoContext.RefreshTokens.Find(query).SetLimit(1).SingleOrDefault(); if (existingToken != null) { var result = await RemoveRefreshToken(existingToken); } mongoContext.RefreshTokens.Insert(token); return true; }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { if (!context.OwinContext.Environment.ContainsKey(IS_REFREHTOKEN_EXPIRED_NAME) || (bool)context.OwinContext.Environment[IS_REFREHTOKEN_EXPIRED_NAME]) { bool result = false; var refreshTokenId = Guid.NewGuid().ToString("n"); var clientId = context.Ticket.Properties.Dictionary.ContainsKey("as:client_id") ? context.Ticket.Properties.Dictionary["as:client_id"] : DUMMY_CLIENT; var refreshTokenLifetime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime") ?? "30"; var token = new RefreshToken() { Id = Helper.GetHash(refreshTokenId), ClientId = clientId, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(Double.Parse(refreshTokenLifetime)) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; // Add current User Id //context.Ticket.Properties.Dictionary.Add("UserId", context.Ticket.Identity.GetUserId()); if (!context.Ticket.Properties.Dictionary.ContainsKey("as:client_id")) { context.Ticket.Properties.Dictionary.Add("as:client_id", clientId); } else { context.Ticket.Properties.Dictionary["as:client_id"] = clientId; } token.ProtectedTicket = context.SerializeTicket(); using (IRepository rep = new ApplicationRepository()) { result = await rep.RefreshTokens.AddAsync(token); } if (result) { context.SetToken(refreshTokenId); } } }
public static String RefreshAccessToken(TembooSession session, String client_id, String client_secret, String refreshToken ) { Console.WriteLine("Refresh YouTube access token"); RefreshToken refreshTokenChoreo = new RefreshToken(session); // Set inputs refreshTokenChoreo.setClientSecret(client_secret); refreshTokenChoreo.setRefreshToken(refreshToken); refreshTokenChoreo.setAccessTokenEndpoint("https://accounts.google.com/o/oauth2/token"); refreshTokenChoreo.setClientID(client_id); // Execute Choreo RefreshTokenResultSet refreshTokenResults = refreshTokenChoreo.execute(); // Print results Console.WriteLine(refreshTokenResults.Response); string s_refresh = refreshTokenResults.Response; JObject json_refresh = JObject.Parse(s_refresh); string accessToken = (string)json_refresh["access_token"]; string expires = (string)json_refresh["expires_in"]; Console.WriteLine("New AccessToken = " + accessToken + " which expires in " + expires + " minutes."); return accessToken; }
public async Task<bool> AddRefreshToken(RefreshToken token) { var existingToken = await dbContext.RefreshTokens.Find(x => x.Subject == token.Subject && x.ClientId == token.ClientId).FirstOrDefaultAsync(); if (existingToken != null) { // FIMXE: No check here on the result, not sure what to do here, if the remove refreshtoken fails, should we continue? var result = await RemoveRefreshToken(existingToken); } dbContext.RefreshTokens.InsertOne(token); return true; }
private async void HubToServerConnect(string ip, string port, string uid, string token) { await Task.Delay(TimeSpan.FromSeconds(0.1)); LobbyManager.Instance.lobbyDialogue.ShowLoggingInStatus("Verifying account details.."); LobbyManager.Instance.lobbyDialogue.serverAddressInput.text = ip; LobbyManager.Instance.lobbyDialogue.serverPortInput.text = port; GameScreenManager.Instance.serverIP = ip; var refreshToken = new RefreshToken(); refreshToken.refreshToken = token; refreshToken.userID = uid; var response = await ServerData.ValidateToken(refreshToken); if (response == null) { LobbyManager.Instance.lobbyDialogue.LoginError( $"Unknown server error. Please check your logs for more information by press F5"); return; } if (!string.IsNullOrEmpty(response.errorMsg)) { Logger.LogError($"Something went wrong with hub token validation {response.errorMsg}", Category.Hub); LobbyManager.Instance.lobbyDialogue.LoginError($"Could not verify your details {response.errorMsg}"); return; } await FirebaseAuth.DefaultInstance.SignInWithCustomTokenAsync(response.message).ContinueWithOnMainThread( async task => { if (task.IsCanceled) { Logger.LogError("Custom token sign in was canceled.", Category.Hub); LobbyManager.Instance.lobbyDialogue.LoginError($"Sign in was cancelled"); return; } if (task.IsFaulted) { Logger.LogError("Task Faulted: " + task.Exception, Category.Hub); LobbyManager.Instance.lobbyDialogue.LoginError($"Task Faulted: " + task.Exception); return; } var success = await ServerData.ValidateUser(task.Result, null, null); if (success) { Logger.Log("Signed in successfully with valid token", Category.Hub); LobbyManager.Instance.lobbyDialogue.ShowCharacterEditor(OnCharacterScreenCloseFromHubConnect); } else { LobbyManager.Instance.lobbyDialogue.LoginError( "Unknown error occured when verifying character settings on the server"); } }); }
public async Task <bool> AddRefreshTokenAsync(RefreshToken refreshToken) { _repository.Add(refreshToken); return(await _repository.UnitOfWork.SaveChangesAsync() > 0); }
public Task UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken) { throw new NotImplementedException(); }
public void InsertOrUpdateGraph(RefreshToken entityGraph) { throw new NotImplementedException(); }
public async Task<SearchResult<IPackageSearchMetadata>> RefreshSearchAsync(RefreshToken refreshToken, CancellationToken cancellationToken) { var searchToken = refreshToken as AggregatedRefreshToken; if (searchToken == null) { throw new InvalidOperationException("Invalid token"); } return await WaitForCompletionOrBailOutAsync(searchToken.SearchString, searchToken.SearchTasks, cancellationToken); }
public async Task <int> Delete(RefreshToken objRefreshToken) { _context.RefreshToken.Remove(objRefreshToken); return(await _context.SaveChangesAsync()); }
public async Task <bool> IsValid(RefreshToken token) { return(await ValidRefreshTokenRepository.TryGet(CreateRedisKeyFromToken(token))); }
public async Task<bool> RemoveRefreshToken(RefreshToken refreshToken) { _ctx.RefreshTokens.Remove(refreshToken); return await _ctx.SaveChangesAsync() > 0; }
public async Task <bool> RemoveRefreshToken(RefreshToken refreshToken) { _dbContext.RefreshTokens.Remove(refreshToken); return(await _dbContext.SaveChangesAsync() > 0); }
public async Task <bool> Save(RefreshToken token) { var expiry = TimeSpan.FromDays(double.Parse(ApplicationSettings.RefreshTokenValidityInDays)); return(await ValidRefreshTokenRepository.Save(CreateRedisKeyFromToken(token), expiry)); }
public Task AddRefreshTokenAsync(RefreshToken rt) { _refreshTokens.AddOrUpdate(rt.Token, rt, (key, val) => rt); return(Task.FromResult(0)); }
public UserResponse(int statusCode, UserDTO user, RefreshToken refreshToken) : base(true, statusCode) { User = user; RefreshToken = refreshToken; }
public void StoreRefToken(RefreshToken reft) { this.refreshTokenRepository.InsertRefreshToken(reft); this.refreshTokenRepository.Save(); }
public async Task <bool> RemoveRefreshToken(RefreshToken refreshToken) { return(await RemoveRefreshToken(refreshToken.Id)); }
public async Task <IActionResult> IsLoggedIn() { string accessToken = HttpContext.Request.Cookies["accessToken"]; string refreshToken = HttpContext.Request.Cookies["refreshToken"]; if (accessToken != null && refreshToken != null) { var tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken token = tokenHandler.ReadJwtToken(accessToken); var expDate = token.ValidTo; var nameid = token.Claims.Where(c => c.Type == "nameid").FirstOrDefault(); var unique_name = token.Claims.Where(c => c.Type == "unique_name").FirstOrDefault(); var email = token.Claims.Where(c => c.Type == "email").FirstOrDefault(); var role = token.Claims.Where(c => c.Type == "role").FirstOrDefault(); User identityUser = await userManager.FindByIdAsync(nameid.Value); if (expDate < DateTime.UtcNow) { RefreshToken refresh = refreshTokenRepository.GetByUserIdAndToken(nameid.Value, refreshToken); if (refresh != null) { if (refresh.ExpiryOn < DateTime.UtcNow || identityUser.IsLocked == true) { await refreshTokenRepository.Remove(refresh.Id); // Set Token Cookie var cookieOptions = new CookieOptions { HttpOnly = true, Secure = true, SameSite = SameSiteMode.None, Expires = DateTime.UtcNow.AddDays(-1) }; HttpContext.Response.Cookies.Append("accessToken", "", cookieOptions); HttpContext.Response.Cookies.Append("refreshToken", "", cookieOptions); return(Ok(new { Results = new { Code = "NotLoggedIn", Description = "Not Logged In Yet!" } })); } else { var key = Encoding.UTF8.GetBytes(jwtBearerTokenSettings.SecretKey); //var role = await userMgr.GetRolesAsync(identityUser); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, nameid.Value), new Claim(ClaimTypes.Name, unique_name.Value), new Claim(ClaimTypes.Email, email.Value), new Claim(ClaimTypes.Role, role.Value) }), Expires = DateTime.UtcNow.AddSeconds(jwtBearerTokenSettings.ExpiryTimeInSeconds), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), Audience = jwtBearerTokenSettings.Audience, Issuer = jwtBearerTokenSettings.Issuer }; // Set Access Token Cookie var accessTokenCookieOptions = new CookieOptions { HttpOnly = true, Secure = true, SameSite = SameSiteMode.None //Expires = DateTime.UtcNow.AddDays(7) }; HttpContext.Response.Cookies.Append("accessToken", tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)), accessTokenCookieOptions); return(Ok(new { Results = new { Info = identityUser, Role = role } })); } } else { return(BadRequest(new { Errors = new { Code = "ExpiredToken", Description = "Token expired!" } })); } } else { return(Ok(new { Results = identityUser, Role = role })); } } return(BadRequest(new { Errors = new { Code = "ExpiredToken", Description = "Token expired!" } })); }
public void AddRefreshToken(RefreshToken token) { _refreshTokens.Add(token); }
public async Task UpdateAsync(RefreshToken token) => await _repository.UpdateAsync(token);
public Task <string> StoreRefreshTokenAsync(RefreshToken refreshToken) { throw new NotImplementedException(); }
/// <summary> /// Updates the refresh token. /// </summary> /// <param name="handle">The handle.</param> /// <param name="refreshToken">The refresh token.</param> /// <param name="client">The client.</param> /// <returns> /// The refresh token handle /// </returns> public virtual async Task <string> UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken, Client client) { _logger.LogDebug("Updating refresh token"); var originalHandle = handle; bool needsCreate = false; bool needsUpdate = false; if (client.RefreshTokenUsage == TokenUsage.OneTimeOnly) { _logger.LogDebug("Token usage is one-time only. Generating new handle"); // delete old one await RefreshTokenStore.RemoveRefreshTokenAsync(handle); // create new one needsCreate = true; } if (client.RefreshTokenExpiration == TokenExpiration.Sliding) { _logger.LogDebug("Refresh token expiration is sliding - extending lifetime"); // make sure we don't exceed absolute exp // cap it at absolute exp var currentLifetime = refreshToken.CreationTime.GetLifetimeInSeconds(); _logger.LogDebug("Current lifetime: " + currentLifetime.ToString()); var newLifetime = currentLifetime + client.SlidingRefreshTokenLifetime; _logger.LogDebug("New lifetime: " + newLifetime.ToString()); if (newLifetime > client.AbsoluteRefreshTokenLifetime) { newLifetime = client.AbsoluteRefreshTokenLifetime; _logger.LogDebug("New lifetime exceeds absolute lifetime, capping it to " + newLifetime.ToString()); } refreshToken.Lifetime = newLifetime; needsUpdate = true; } if (needsCreate) { handle = await RefreshTokenStore.StoreRefreshTokenAsync(refreshToken); _logger.LogDebug("Created refresh token in store"); } else if (needsUpdate) { await RefreshTokenStore.UpdateRefreshTokenAsync(handle, refreshToken); _logger.LogDebug("Updated refresh token in store"); } else { _logger.LogDebug("No updates to refresh token done"); } return(handle); }
public async Task<RefreshToken> GenerateRefreshToken(RefreshToken token) { return await _db.RefreshTokens.Where(r => r.Subject == token.Subject && r.ClientId == token.ClientId && r.DeviceId == token.DeviceId).FirstOrDefaultAsync(); }
public async Task<bool> RemoveRefreshToken(RefreshToken refreshToken) { return await RemoveRefreshToken(refreshToken.Id); }
public void Delete(RefreshToken token) { _context.RefreshTokens.Remove(token); }
public async Task Valid_RefreshToken_Request_using_Restricted_Client() { var refreshToken = new RefreshToken { AccessToken = new Token("access_token"), ClientId = "roclient_restricted_refresh", LifeTime = 600, Handle = Guid.NewGuid().ToString(), CreationTime = DateTime.UtcNow }; var store = new InMemoryRefreshTokenStore(); await store.StoreAsync(refreshToken.Handle, refreshToken); var client = await _clients.FindClientByIdAsync("roclient_restricted_refresh"); var validator = Factory.CreateTokenValidator( refreshTokens: store); var parameters = new NameValueCollection(); parameters.Add(Constants.TokenRequest.GrantType, "refresh_token"); parameters.Add(Constants.TokenRequest.RefreshToken, refreshToken.Handle); var result = await validator.ValidateRequestAsync(parameters, client); Assert.IsFalse(result.IsError); }
private void DeleteToken(User user, RefreshToken refreshToken) { user.RefreshTokens.Remove(refreshToken); }
private async Task <AuthenticationResult> GenerateAuthorizationForUserAsync(User user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.Key); var claims = new List <Claim> { new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Sub, user.Email), new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Email, user.Email), new Claim("id", user.Id), }; var userClaims = await _userManager.GetClaimsAsync(user); claims.AddRange(userClaims); var userRoles = await _userManager.GetRolesAsync(user); foreach (var userRole in userRoles) { claims.Add(new Claim(ClaimTypes.Role, userRole)); var role = await _roleManager.FindByNameAsync(userRole); if (role == null) { continue; } var roleClaims = await _roleManager.GetClaimsAsync(role); foreach (var roleClaim in roleClaims) { if (claims.Contains(roleClaim)) { continue; } claims.Add(roleClaim); } } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.Add(_jwtSettings.TokenLifeTime), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var refreshToken = new RefreshToken { Token = Guid.NewGuid().ToString(), JwtId = token.Id, UserId = user.Id, CreationDate = DateTime.UtcNow, ExpiryDate = DateTime.UtcNow.AddMonths(1), }; await _context.RefreshTokens.AddAsync(refreshToken); await _context.SaveChangesAsync(); return(new AuthenticationResult { Success = true, Token = tokenHandler.WriteToken(token), RefreshToken = refreshToken.Token }); }
private async Task <AuthenticationResult> GenerateAuthenticationResultForUser(IdentityUser user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret); var claims = new List <Claim> { new Claim(type: JwtRegisteredClaimNames.Sub, value: user.Email), new Claim(type: JwtRegisteredClaimNames.Jti, value: Guid.NewGuid().ToString()), new Claim(type: JwtRegisteredClaimNames.Email, value: user.Email), new Claim(type: "id", value: user.Id) }; var userClaims = await _userManager.GetClaimsAsync(user); claims.AddRange(userClaims); //var userRoles = await _userManager.GetRolesAsync(user); //foreach (var userRole in userRoles) //{ // claims.Add(new Claim(ClaimTypes.Role, userRole)); // var role = await _roleManager.FindByNameAsync(userRole); // if (role == null) continue; // var roleClaims = await _roleManager.GetClaimsAsync(role); // foreach (var roleClaim in roleClaims) // { // if (claims.Contains(roleClaim)) // continue; // claims.Add(roleClaim); // } //} var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims: claims), Expires = DateTime.UtcNow.Add(_jwtSettings.TokenLifetime), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var refreshToken = new RefreshToken { JwtId = token.Id, UserId = user.Id, TokenCreationDate = DateTime.UtcNow, ExpiryDate = DateTime.UtcNow.AddMonths(6) }; await _dataContext.RefreshTokens.AddAsync(refreshToken); await _dataContext.SaveChangesAsync(); return(new AuthenticationResult { Success = true, Token = tokenHandler.WriteToken(token), RefreshRoken = refreshToken.Token }); }
public override async Task CreateAsync([NotNull] AuthenticationTokenCreateContext context) { if (context.OwinContext == null) { return; } var properties = context.Ticket?.Properties; if (properties == null) { return; } var identity = context.Ticket.Identity; if (identity == null) { return; } if (!Guid.TryParse(identity.FindFirst(IntersectClaimTypes.ClientId)?.Value, out var clientId)) { Log.Diagnostic( "Received invalid client id '{0}'.", identity.FindFirst(IntersectClaimTypes.UserId)?.Value ); } var identifier = identity.FindFirst(IntersectClaimTypes.UserId)?.Value; if (!Guid.TryParse(identifier, out var userId)) { return; } var userName = identity.FindFirst(IntersectClaimTypes.UserName)?.Value; var issued = DateTime.UtcNow; var expires = issued.AddMinutes(Configuration.RefreshTokenLifetime); var ticketId = context.OwinContext.Get <Guid>("ticket_id"); if (ticketId == Guid.Empty) { identity.FindAll(IntersectClaimTypes.TicketId) ?.ToList() .ForEach( claim => { if (!Guid.TryParse(claim?.Value, out var guid) || guid == Guid.Empty) { identity.TryRemoveClaim(claim); } } ); var ticketIdClaim = identity.FindFirst(IntersectClaimTypes.TicketId); if (ticketIdClaim == null || !Guid.TryParse(ticketIdClaim.Value, out ticketId)) { ticketId = Guid.NewGuid(); identity.AddClaim(new Claim(IntersectClaimTypes.TicketId, ticketId.ToString())); } } var token = new RefreshToken { UserId = userId, ClientId = clientId, Subject = userName, Issued = issued, Expires = expires, TicketId = ticketId }; properties.IssuedUtc = issued; properties.ExpiresUtc = expires; token.Ticket = context.SerializeTicket(); if (await RefreshToken.Add(token, true)) { context.SetToken(token.Id.ToString()); } }
public bool Equals(RefreshToken other) => null != other && (Token == other.Token);
public static async Task RaiseRefreshTokenIssuedEventAsync(this IEventService events, string id, RefreshToken token) { var evt = new Event <RefreshTokenDetails>( EventConstants.Categories.TokenService, "Refresh token issued", EventTypes.Information, EventConstants.Ids.RefreshTokenIssued); evt.DetailsFunc = () => new RefreshTokenDetails { HandleId = id, ClientId = token.ClientId, Scopes = token.Scopes, SubjectId = token.SubjectId, Lifetime = token.Lifetime, Version = token.Version }; await events.RaiseEventAsync(evt); }
public UpDateRefreshtoken(RefreshToken refreshToken) { RefreshTokens = refreshToken; }
public static async Task RaiseSuccessfulRefreshTokenRefreshEventAsync(this IEventService events, string oldHandle, string newHandle, RefreshToken token) { var evt = new Event <RefreshTokenRefreshDetails>( EventConstants.Categories.TokenService, "Refresh token refresh success", EventTypes.Success, EventConstants.Ids.RefreshTokenRefreshedSuccess); evt.Details = new RefreshTokenRefreshDetails { OldHandle = ObfuscateToken(oldHandle), NewHandle = ObfuscateToken(newHandle), ClientId = token.ClientId, Lifetime = token.Lifetime }; await events.RaiseEventAsync(evt); }
public async Task <bool> Delete(RefreshToken token) { return(await ValidRefreshTokenRepository.Delete(CreateRedisKeyFromToken(token))); }
public async Task <Response <TokensDto> > GenerateTokensAsync(User user) { var secretKey = _configurationService.GetValue("Jwt:Key"); var issuer = _configurationService.GetValue("Jwt:Issuer"); var expirationDate = DateTime.Now.AddDays(Convert.ToDouble(_configurationService.GetValue("Jwt:ExpDays"))); var result = new Response <TokensDto>() { Model = new TokensDto() }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.GivenName, user.Username), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Sid, user.Id.ToString()), new Claim(ClaimTypes.Hash, Guid.NewGuid().ToString()), new Claim(ClaimTypes.Role, user.IsAdmin ? "Admin" : "User") }; var token = new JwtSecurityToken( issuer, issuer, claims, expires: expirationDate, signingCredentials: creds ); result.Model.Token = new JwtSecurityTokenHandler().WriteToken(token); result.Model.TokenExpirationDate = expirationDate; var refreshTokenRaw = user.Email + Guid.NewGuid() + user.Id + DateTime.Now.ToShortDateString() + secretKey; var refreshToken = new RefreshToken() { UserId = user.Id, Token = refreshTokenRaw.ToHash(), TokenExpirationDate = DateTime.Now.AddDays(Convert.ToDouble(_configurationService.GetValue("Jwt:ExpRefreshToken"))) }; result.Model.RefreshToken = refreshToken.Token; result.Model.RefreshTokenExpirationDate = refreshToken.TokenExpirationDate; var existingRefreshToken = _tokenRepository.Get(t => t.UserId == user.Id); if (existingRefreshToken != null) { var removingResult = await _tokenRepository.RemoveAsync(existingRefreshToken); if (!removingResult) { result.Errors.Add("A critical error occurred, please constant the websites support or try again later."); return(result); } } var insertResult = await _tokenRepository.InsertAsync(refreshToken); if (insertResult) { return(result); } result.Errors.Add("A critical error occurred, please constant the websites support or try again later."); return(result); }
public async void RevokeRefreshToken(string token) { RefreshToken refreshToken = await this.GetExistingToken(token); refreshToken.Revoked = true; }
public async Task <AuthUserViewModel> Handle(RegisterUserCommand request, CancellationToken cancellationToken) { try { // check if default role exists if (!await _roleManager.RoleExistsAsync(_configurationSection["defaultRole"])) { throw new Exception("Role " + _configurationSection["defaultRole"] + " does not exist"); } ; var existingUser = await _userManager.FindByEmailAsync(request.UserEmail); if (existingUser != null) { throw new Exception(" User with Email " + request.UserEmail + " exists"); } var appUser = new IdentityUser { Email = request.UserEmail, UserName = request.UserEmail, PhoneNumber = request.PhoneNumber, PhoneNumberConfirmed = false }; var identityResult = await _userManager.CreateAsync(appUser, request.UserPassWord); if (identityResult.Succeeded) { var userRoleResult = await _userManager.AddToRoleAsync(appUser, _configurationSection["defaultRole"]); } else { throw new Exception(String.Join(" ", identityResult.Errors.Select(e => e.Description))); } var emailTokenBytes = Encoding.UTF8.GetBytes(await _userManager.GenerateEmailConfirmationTokenAsync(appUser)); var confirmEmailToken = WebEncoders.Base64UrlEncode(emailTokenBytes); var user = new User { FirstName = request.FirstName, LastName = request.LastName, UserEmail = request.UserEmail, CreatedDate = _dateTime.Now, EmailConfirmationToken = "Check Email", Id = appUser.Id, }; _appDbContext.AppUser.Add(user); var refreshToken = _tokenFactory.GenerateToken(); var userRoles = await _userManager.GetRolesAsync(appUser); var userToken = await _jwtFactory.GenerateEncodedToken(appUser.Id, appUser.UserName, userRoles); var userRefreshToken = new RefreshToken { CreatedBy = appUser.Id, CreatedDate = _dateTime.Now, LastEditedBy = appUser.Id, LastEditedDate = _dateTime.Now, Expires = _dateTime.Now.AddSeconds((double)userToken.ExpiresIn), UserId = appUser.Id, Token = refreshToken, RemoteIpAddress = request.RemoteIPAddress }; _appDbContext.RefreshToken.Add(userRefreshToken); await _appDbContext.SaveChangesAsync(cancellationToken); //Publish Email Notification await _mediator.Publish(new PublishEmailNotificationCommand { MessageType = "EMAIL", NotifType = NotificationMessageType.CONFIRM_EMAIL, MessageLink = user.Id + "/" + confirmEmailToken, Recipient = user.UserEmail, RecipientName = user.FirstName + " " + user.LastName }, cancellationToken); return(new AuthUserViewModel { UserDetails = new UserDTO { FirstName = user.FirstName, LastName = user.LastName, UserEmail = user.UserEmail, Id = user.Id, }, UserToken = new AccessTokenViewModel { AccessToken = userToken, RefreshToken = refreshToken }, StatusMessage = "Success", RequestStatus = 1 }); } catch (Exception e) { return(new AuthUserViewModel { RequestStatus = 0, StatusMessage = e.Message }); } }