public void CreateRefreshToken(RefreshTokenModel model) { var entity = _mapper.Map <RefreshToken>(model); _apiTestContext.RefreshToken.Add(entity); _apiTestContext.SaveChanges(); }
public virtual async Task <IActionResult> Refresh([FromBody] RefreshTokenModel tokenModel) { if (tokenModel is null) { return(BadRequest(new AuthResponseModel { IsAuthSuccessful = false, ErrorMessage = "Invalid client request" })); } var principal = _tokenService.GetPrincipalFromExpiredToken(tokenModel.Token); var username = principal?.Identity?.Name; var user = await _userManager.FindByEmailAsync(username); if (user == null || user.RefreshToken != tokenModel.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { return(BadRequest(new AuthResponseModel { IsAuthSuccessful = false, ErrorMessage = "Invalid client request" })); } var signingCredentials = _tokenService.GetSigningCredentials(); var claims = await _tokenService.GetClaims(user); var tokenOptions = _tokenService.GenerateTokenOptions(signingCredentials, claims); var token = new JwtSecurityTokenHandler().WriteToken(tokenOptions); user.RefreshToken = _tokenService.GenerateRefreshToken(); await _userManager.UpdateAsync(user); return(Ok(new AuthResponseModel { Token = token, RefreshToken = user.RefreshToken, IsAuthSuccessful = true })); }
public IActionResult Refresh([FromBody] RefreshTokenModel refreshToken) { try { var principal = GetPrincipalFromExpiredToken(refreshToken.Token); var username = principal.Identity.Name; var savedRefreshToken = ""; savedRefreshToken = _userService.GetUserRefreshToken(username); //retrieve the refresh token from a data store if (savedRefreshToken != refreshToken.RefreshToken) { return(Ok(new { Status = PublicResultStatusCodes.NotAuthorized })); } var newJwtToken = _jwtTokenGenerator.GenerateAccessTokenWithClaimsPrincipal(username, principal.Claims); var newRefreshToken = RefreshTokenHelper.GenerateRefreshToken(); _userService.SaveUserRefreshToken(username, newRefreshToken); return(Ok(new { Status = PublicResultStatusCodes.Done, Data = new List <object> { new{ RefreshToken = newRefreshToken, Token = newJwtToken.AccessToken, ValidTokenTimeInMinutes = _token.ValidTimeInMinutes, ValidDateTimeToken = DateTime.Now.AddMinutes(_token.ValidTimeInMinutes) } } })); } catch (SecurityTokenException ex) { return(Ok(new { Status = PublicResultStatusCodes.NotAuthorized })); } }
public TokenResponseModel SignIn(string username) { var accessToken = new AccessTokenModel() { Token = CreateAccessToken(username), TokenType = "bearer", ExpiresIn = ExpirationTimeInSeconds }; var refreshToken = new RefreshTokenModel() { Token = CreateRefreshToken(username), IsRevoked = false, User = username }; _refreshTokens.Add(refreshToken); var response = new TokenResponseModel() { AccessToken = accessToken, RefreshToken = refreshToken.Token }; return(response); }
public async Task <ActionResult <AuthTokenModel> > Refresh(RefreshTokenModel refreshTokenModel) { var principal = GetPrincipalFromExpiredToken(refreshTokenModel.Token); var userId = principal.GetLoggedInUserId();; if (string.IsNullOrEmpty(userId)) { throw new SecurityTokenException("Invalid refresh token"); } var user = await userRepository.Get(userId); var oldRefreshToken = await refreshTokenRepository.Get(userId, refreshTokenModel.RefreshToken); if (user == null || oldRefreshToken == null) { throw new SecurityTokenException("Invalid refresh token"); } await refreshTokenRepository.Delete(userId, oldRefreshToken.Id); var newToken = await GenerateToken(user); return(Ok(newToken)); }
public TokenModel RefreshToken(RefreshTokenModel tokenModel) { var jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(tokenModel.OldToken); var claimsIdentity = new ClaimsIdentity(jwtToken.Claims); return(CreateToken(claimsIdentity)); }
public async Task <IActionResult> RefeshToken(RefreshTokenModel model) { var client = _httpClientFactory.CreateClient("token_client"); var tokenClient = new TokenClient(client, new TokenClientOptions { Address = $"{CommonHelper.GetWebLocation()}connect/token", ClientId = "client", ClientSecret = "secret" }); // var tokenClient = new TokenClient( $"{CommonHelper.GetWebLocation()}connect/token", "client", "secret" ); var tokenResponse = await tokenClient.RequestRefreshTokenAsync(model.RefreshToken); if (tokenResponse.IsError) { return(Error(500, tokenResponse.ErrorType.ToString(), tokenResponse.Error + "," + tokenResponse.ErrorDescription)); } return(Ok(new { token = tokenResponse.AccessToken, expiresIn = tokenResponse.ExpiresIn, // 秒 expiresAtUtc = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn), refreshToken = tokenResponse.RefreshToken, })); }
private object SuccessObject(DateTime createDate, DateTime expirationDate, string token, int idUsuario, TimeSpan finalExpiration) { var resultado = new { autenticated = true, created = createDate.ToString("yyyy-MM-dd HH:mm:ss"), expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"), accessToken = token, refreshToken = Guid.NewGuid().ToString().Replace("-", String.Empty), message = "OK" }; // Armazena o refresh token em cache através do Redis var refreshTokenData = new RefreshTokenModel(); refreshTokenData.RefreshToken = resultado.refreshToken; refreshTokenData.UserID = idUsuario; DistributedCacheEntryOptions opcoesCache = new DistributedCacheEntryOptions(); opcoesCache.SetAbsoluteExpiration(finalExpiration); _cache.SetString(resultado.refreshToken, JsonConvert.SerializeObject(refreshTokenData), opcoesCache); return(resultado); }
public async Task <IActionResult> Refresh(RefreshTokenModel model) { var gatewayUrl = _configuration.GetValue <string>("GatewayUrl"); var requestBodyParams = new List <string> { "grant_type=refresh_token", $"client_id={_clientDetails.Key}", $"client_secret={_clientDetails.Secret}", $"refresh_token={model.RefreshToken}" }; var restClient = new RestClient($"{gatewayUrl}/connect/token"); var request = new RestRequest(Method.POST); request.AddHeader("Cache-Control", "no-cache"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("undefined", string.Join("&", requestBodyParams), ParameterType.RequestBody); IRestResponse response = restClient.Execute(request); dynamic data = JsonConvert.DeserializeObject(response.Content); var viewModel = new ConsentedViewModel(); viewModel.AccessToken = data.access_token; viewModel.ExpiresIn = data.expires_in; viewModel.TokenType = data.token_type; viewModel.RefreshToken = data.refresh_token; return(View("Index", viewModel)); }
public async Task <bool> RevokeRefreshTokenAsync(RefreshTokenModel refreshToken) { refreshToken.Revoked = true; var result = await _refreshTokenRepository.ReplaceAsync(refreshToken, x => x.Token == refreshToken.Token); return(result); }
public IActionResult RefreshToken([FromBody] RefreshTokenModel model) { var userId = TokenHelper.GetUserIdFromRefreshToken(model.RefreshToken); if (!db.CheckRefreshToken(model.RefreshToken, userId)) { return(StatusCode(401, new ErrorDetails() { errorId = ErrorList.InputDataError.Id, errorMessage = ErrorList.InputDataError.Description })); } db.DeleteRefreshToken(model.RefreshToken, userId); var profile = db.GetProfile(userId); var user = new UserModel { Name = profile.Name, Email = profile.Email, Role = profile.Role.Name, Id = profile.UserId }; if (user != null) { var accessTokenExp = DateTime.Now.AddMinutes(30); var refreshTokenExp = DateTime.Now.AddYears(1); var accessToken = BuildAccessToken(user, accessTokenExp); var refreshToken = BuildRefreshToken(user, refreshTokenExp); long unixExp = ((DateTimeOffset)accessTokenExp).ToUnixTimeSeconds(); db.AddRefreshToken(refreshToken, user.Id, DateTime.Now, refreshTokenExp); var response = new { response = new { accessToken, refreshToken, expiresIn = unixExp } }; return(Ok(response)); } throw new Exception("Unknown error"); }
// Token and refresh Token private async void RefreshToken() { var IdToken = await SecureStorage.GetAsync("IdToken"); using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage(new HttpMethod("POST"), RefreshIdTokenUri)) { var refreshToken = await SecureStorage.GetAsync("RefreshToken"); RefreshTokenModel rtm = new RefreshTokenModel() { GrantType = "refresh_token", RefreshToken = refreshToken }; request.Content = new StringContent(JsonConvert.SerializeObject(rtm)); var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { var jResponse = await response.Content.ReadAsStringAsync(); var jData = JsonConvert.DeserializeObject <JObject>(jResponse); Preferences.Set("lastRefreshAt", DateTime.UtcNow); await SecureStorage.SetAsync("IdToken", jData.GetValue("access_token").ToString()); } else { await Application.Current.MainPage.DisplayAlert("", "Can't refresh token, log out and login again", "OK"); } } } }
public UserAuthenticationModel IsAuthenticated(RefreshTokenModel request) { var result = _userAuthentication.Get(request.Id); if (result != null && result.IsAuthenticated) { var claim = new[] { new Claim(ClaimTypes.Name, result.Name), new Claim("UserInfo", result.Id.ToString() + '|' + result.Name + '|' + result.RoleId.ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken( _tokenManagement.Issuer, _tokenManagement.Audience, claim, notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration), signingCredentials: credentials ); result.Token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return(result); } else { return new UserAuthenticationModel { IsAuthenticated = false } }; } }
/// <summary> /// Refresh IotConnect token. Requires bearer token and refresh token. /// </summary> /// <param name="token">Bearer token.</param> /// <param name="refreshTokenModel">The refresh token model.</param> /// <returns></returns> public async Task <DataResponse <LoginResult> > RefreshToken(string token, RefreshTokenModel refreshTokenModel) { try { var portalAuthApi = await _ioTConnectAPIDiscovery.GetPortalUrl(_envCode, _solutionKey, IoTConnectBaseURLType.AuthBaseUrl); string accessTokenUrl = string.Concat(portalAuthApi, AuthApi.RefreshTokenUrl); string formattedUrl = String.Format(accessTokenUrl, Constants.authVersion); var data = await formattedUrl .WithHeaders(new { Content_type = Constants.contentType, Authorization = Constants.bearerTokenType + token }) .PostJsonAsync(refreshTokenModel).ReceiveJson <LoginResult>(); return(new DataResponse <LoginResult>(null) { data = data, status = true }); } catch (IoTConnectException ex) { return(new DataResponse <LoginResult>(null) { errorMessages = ex.error, status = false }); }; }
public async Task <IActionResult> RefeshToken([FromBody] RefreshTokenModel model) { var principal = _tokenService.GetPrincipalFromExpiredToken(model.Token); if (principal == null) { return(BadRequest(new { Error = "Invalid token" })); } var user = await _userManager.GetUserAsync(principal); var verifyRefreshTokenResult = _userManager.PasswordHasher.VerifyHashedPassword(user, user.RefreshTokenHash, model.RefreshToken); if (verifyRefreshTokenResult == PasswordVerificationResult.Success) { var roles = await _userManager.GetRolesAsync(user); var claims = await BuildClaims(user); var newToken = _tokenService.GenerateAccessToken(claims); return(Ok(new { token = newToken, refreshToken = model.RefreshToken, roles = roles })); } return(Forbid()); }
public IHttpActionResult RefreshToken([FromBody] RefreshTokenModel model) { var decoded = JwtHelper.DecodeToken(model.RefreshToken, TokenAudiences.RefreshToken); if (decoded == null) { return(BadRequest()); } string userId = decoded.FindFirst(ClaimTypes.NameIdentifier)?.Value; var user = DB.Users.IncludeOptimized(x => x.Claims).FirstOrDefault(x => x.Id == userId); if (user == null) { return(BadRequest()); } return(Ok(new LoginResponse() { RefreshToken = JwtHelper.SignToken(user, expires: DateTime.UtcNow.AddMonths(1), audience: TokenAudiences.RefreshToken), AccessToken = JwtHelper.SignToken(user, audience: TokenAudiences.Universal), ExpiresAt = DateTime.UtcNow.AddDays(3), IssuedAt = DateTime.UtcNow })); }
public async Task <Result> RefreshTokenAsync() { try { var refreshToken = new RefreshTokenModel() { RefreshToken = await _currentUser.GetAuthRefreshToken(), Token = await _currentUser.GetAuthToken() }; var loginAsJson = JsonConvert.SerializeObject(refreshToken); var response = await httpClient.PostAsync("api/v1/OAuth/RefreshToken", new StringContent(loginAsJson, Encoding.UTF8, "application/json")); var result = JsonConvert.DeserializeObject <AuthenticationResult>(await response.Content.ReadAsStringAsync()); if (!response.IsSuccessStatusCode) { return(Result.Failure(result.EnError, result.FaError)); } await SetAuthentication(result.Token, result.RefreshToken); return(Result.Success()); } catch (Exception) { return(CommonResults.InternalServerError("Internal Server Error", "سرور در حال بارگذاری می باشد")); } }
public async Task <IActionResult> RefreshToken([FromBody] RefreshTokenModel refreshToken) { if (string.IsNullOrWhiteSpace(refreshToken.RefreshToken)) { return(Unauthorized()); } var refreshTokenModel = _DbContext.RefreshTokens.Include(e => e.User).SingleOrDefault(e => e.Token == refreshToken.RefreshToken); if (refreshTokenModel == null) { return(Unauthorized()); } if (await _SignInManager.CanSignInAsync(refreshTokenModel.User) == false) { return(Unauthorized()); } if (_UserManager.SupportsUserLockout && await _UserManager.IsLockedOutAsync(refreshTokenModel.User)) { return(Unauthorized()); } var user = refreshTokenModel.User; var token = GetRefreshToken(user); return(Ok(token)); }
public async Task <object> RefreshToken([FromBody] RefreshTokenModel refreshTokenModel) { var refreshToken = refreshTokenModel.RefreshToken; if (string.IsNullOrWhiteSpace(refreshToken)) { return(BadRequest("refreshToken is not set.")); } return(await ExecuteSafely(() => { var token = _tokenService.GetTokenByRefreshToken(refreshToken); if (token == null) { throw new RefreshTokenExpiredException(); } var oauthToken = _tokenService.CreateOAuthToken(token.User); return new { access_token = oauthToken.AccessToken, expires_in = oauthToken.ExpiresIn, refresh_token = oauthToken.RefreshToken }; })); }
private async Task <AccessTokenModel> GenerateToken( string login, SigningConfiguration signingConfigurations, TokenConfiguration tokenConfigurations, IDistributedCache cache) { var account = await _accountService.GetAccountInformation(login); ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(login, "Login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim("user", login), new Claim(ClaimTypes.Role, account.group_id.ToString()) } ); DateTime creationDate = DateTime.Now; DateTime expirationDate = creationDate + TimeSpan.FromSeconds(tokenConfigurations.TokenExpiration); TimeSpan finalExpiration = TimeSpan.FromSeconds(tokenConfigurations.RefreshTokenExpiration); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = tokenConfigurations.Issuer, Audience = tokenConfigurations.Audience, SigningCredentials = signingConfigurations.SigningCredentials, Subject = identity, NotBefore = creationDate, Expires = expirationDate }); var token = handler.WriteToken(securityToken); var result = new AccessTokenModel() { Authenticated = true, Created = creationDate.ToString("yyyy-MM-dd HH:mm:ss"), Expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"), AccessToken = token, RefreshToken = RefreshToken.Generate(), Message = "OK" }; var refreshTokenData = new RefreshTokenModel(); refreshTokenData.RefreshToken = result.RefreshToken; refreshTokenData.Login = login; DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions(); cacheOptions.SetAbsoluteExpiration(finalExpiration); await cache.SetStringAsync(result.RefreshToken, JsonConvert.SerializeObject(refreshTokenData), cacheOptions); return(result); }
private RefreshTokenModel CreateRefreshToken(UserModel user) { var token = new RefreshTokenModel(); SetBaseToken(token, user); return(token); }
public async Task SaveRefreshToken(string username, RefreshTokenModel refreshToken) { var user = await _context.Users.FirstOrDefaultAsync(x => x.Username == username); user.RefreshToken = refreshToken.Token; user.RefreshTokenExpiration = refreshToken.RefreshTokenExpiration; await _context.SaveChangesAsync(); }
/// <summary> /// Save refresh token into storage. /// </summary> /// <param name="email">The owner refresh token.</param> /// <param name="refreshToken">The refresh token value.</param> private void SaveRefreshToken(string email, string refreshToken) { var model = new RefreshTokenModel { RefreshToken = refreshToken }; RedisCacheHandler.SetValue(email, model); }
public JWTResponse(string email, string jwtToken, string refreshToken, DateTime expiryDate, RefreshTokenModel refreshModelToken) { Email = email; JwtToken = jwtToken; RefreshToken = refreshToken; ExpiryDate = expiryDate; RefreshTokenModel = refreshModelToken; }
public async Task <ApiResponse> RefreshToken([FromBody] RefreshTokenModel refreshToken) { var refreshTokenBytes = Convert.FromBase64String(refreshToken.Value); var deserializedRefreshToken = JsonConvert.DeserializeObject <RefreshToken>(Encoding.ASCII.GetString(refreshTokenBytes)); var user = await _dbContext.AuthUsers .Include(x => x.RefreshTokens) .Where(x => x.RefreshTokens.Any(a => a.Token == deserializedRefreshToken.Token)) .SingleOrDefaultAsync(); _ = user ?? throw new ApiException("Provided token was invalid or not found", StatusCodes.Status401Unauthorized); var loadedToken = user.RefreshTokens.SingleOrDefault(x => x.Token == deserializedRefreshToken.Token); if (!loadedToken.IsActive) { throw new ApiException("Provided token was ivnalid or not found", StatusCodes.Status401Unauthorized); } var token = user.RefreshTokens.SingleOrDefault(x => x.Token == deserializedRefreshToken.Token); // ReSharper disable once PossibleNullReferenceException token.Revoked = DateTime.Now; var newJwtToken = _tokenGenerator.GenerateJwtToken(user.AppUserId); var newRefreshToken = _tokenGenerator.GenerateRefreshToken(); user.RefreshTokens.Add(newRefreshToken); _dbContext.Set <AuthUser>().Update(user); try { await _dbContext.SaveChangesAsync(); } catch (DbUpdateException ex) { throw new ApiException(ex); } var refreshTokenByteArray = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(newRefreshToken)); try { var jwtToken = new JwtSecurityTokenHandler().WriteToken(newJwtToken); return(new ApiResponse(new { token = jwtToken, expires = newJwtToken.ValidTo, refreshToken = Convert.ToBase64String(refreshTokenByteArray) })); } catch (Exception ex) { throw new ApiException(ex); } }
/// <summary> /// CreateRefreshToken async /// </summary> /// <param name="context"></param> /// <returns></returns> public async override Task CreateAsync(AuthenticationTokenCreateContext context) { try { //Create(context); // var clientid = context.Ticket.Properties.Dictionary["as:client_id"]; object owinCollection; context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out owinCollection); var grantType = ((FormCollection)owinCollection)?.GetValues("grant_type").FirstOrDefault(); var clientId = ((FormCollection)owinCollection)?.GetValues("client_id").FirstOrDefault(); if (grantType == null) { return; } if (clientId == null) { return; } var refreshTokenId = Guid.NewGuid().ToString("n"); var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime"); var token = new RefreshTokenModel() { RefToken = Utility.GetHash(refreshTokenId), ClientId = clientId, UserName = 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 existingToken = await _refreshTokenService.GetByClientIdAndUserNameAsync(token.ClientId, token.UserName); if (existingToken != null) { await _refreshTokenService.DeleteAsync(existingToken.Id); } await _refreshTokenService.InsertAsync(token); context.SetToken(refreshTokenId); } catch (Exception ex) { _logger.Error(GetType(), ex, "RefreshTokenProvider/CreateAsync"); throw ex; } }
public IActionResult Refresh([FromBody] RefreshTokenModel model) { var principal = GetPrincipalFromExpiredToken(model); var username = principal.Identity.Name; var newJwtToken = GenerateToken(principal.Claims); return(Ok(new { token = newJwtToken })); }
public IActionResult Refresh([FromBody] RefreshTokenModel model) { var principal = GetPrincipalFromExpiredToken(model.ExpiredToken); var username = principal.Identity.Name; return(new ObjectResult(new { token = GenerateToken(principal.Claims) })); }
public async Task <IActionResult> RefreshToken([FromBody] RefreshTokenModel refreshTokenModel) { try { string access_token = await _tekonManager.ValidateRefreshTokenAsync(refreshTokenModel.AccessToken, refreshTokenModel.RefreshToken); return(Ok(new { access_token })); } catch (SecurityTokenException ex) { return(BadRequest(new { error = ex.Message })); } }
public async Task <RefreshTokenModel> RefreshToken(RefreshTokenModel tokens) { var formData = new Dictionary <string, string> { { "accessToken", tokens.AccessToken }, { "refreshToken", tokens.RefreshToken }, }; return(await PostFormUrlEncodedContentAsync <RefreshTokenModel>("hobbyConnect/refreshToken", formData)); }