public string RefreshToken([FromBody] RefreshTokenRequest request) { ResponseData resp = new ResponseData(); string accesstoken = request.accesstoken; string oldrefreshtoken = request.refreshtoken; User u = MySQLDapperQueries.GetUserByAccessTokenAndRefreshToken(accesstoken, oldrefreshtoken); // if refresh token if expired... return to login page // if not use it to generate new access token and new refreshtoken if (u == null) { resp = new ResponseData { Code = "506", Message = "invalid user", Data = null }; } else if (u.refresh_token_expiration < DateTime.Now) { // return to login page resp = new ResponseData { Code = "700", Message = "refresh token has expired", Data = null }; } else { RefreshToken rtoken = Authentication.RefreshToken(GetIP(), accesstoken, oldrefreshtoken); u.refresh_token = rtoken.Token; u.refresh_token_expiration = rtoken.ExpiryDate; AccessToken atoken = Authentication.GenerateAccessToken(GetIP()); u.token = atoken.Token; u.token_expiration = atoken.ExpiryDate; int updatedrow = MySQLDapperQueries.UpdateUserTokens(u.id, u.token, u.token_expiration, u.refresh_token, u.refresh_token_expiration); if (updatedrow > 0) { resp = new ResponseData { Code = "200", Message = "Tokens Refreshed", Data = new { Accesstoken = u.token, RefreshToken = u.refresh_token, ID = u.id } }; } else { resp = new ResponseData { Code = "508", Message = "Couldn't Refresh Tokens", Data = null }; } } return(JsonConvert.SerializeObject(resp, Formatting.None)); }
private string _getKey(RefreshTokenRequest r) { return($"RefreshTokenRequest{r.ClientId}{r.RefreshToken}{r.Audience}{r.Scope}"); }
public async Task <AuthenticationResult> RefreshTokenRequest([FromBody] RefreshTokenRequest request) { return(await _identityService.RefreshTokenAsync(request.Token, request.RefreshToken)); }
static async Task Main() { // These credentials are a test account. // I don't care about the data. // of course, you would provide your own. var httpClient = new HttpClient(); var clientId = ClientId("tj7a3rtbs5dmsz2sbwxx3phd"); var clientSecret = ClientSecret("EEecE6bBYz"); var redirectUri = RedirectUri("https://localhost"); // These are meant to be created once and used throughout your application. // Inject into your DI container, or whatever your preference. AccessTokenRequest requestAccessToken = AccessTokenRequest(httpClient, clientId, clientSecret, redirectUri); RefreshTokenRequest requestRefreshToken = RefreshTokenRequest(httpClient, clientId, clientSecret); /* * =============== * STEP 1 * =============== * Infusionsoft does not provide a way for an application to automatically authenticate. * They currently require a user's consent. * * To grab an access code from infusionsoft, complete the following steps. * 1. Point your browser to: * https://accounts.infusionsoft.com/app/oauth/authorize?client_id=tj7a3rtbs5dmsz2sbwxx3phd&response_type=code&redirect_uri=https://localhost * 2. Click the "Allow" button * 3. Copy the code that is returned in the adddress bar of your browser * 4. Paste the code below in the AccessCode * =============== */ // Utilize cache so we can run this program many times without the above hassle. // This is not part of the core library. var authorization = await AuthorizationInfoFromCache().IfNoneAsync(() => requestAccessToken(AccessCode("72ycjp593vxzgaf9f7fxhus3")).Map(CacheAuthorizationInfo) ); var client = new InfusioClient(httpClient, authorization); /* * =============== * STEP 2 * =============== * Describe the Infusionsoft operation that want to execute. * InfusioOps are composable. You combine any number of InfusioOps together to form one InfusioOp. * You're not stuck with running one operation at a time like you're probably used to traditionally. * =============== */ InfusioOp <FullContact> operation = CustomOperations.AddTagToContact( new Tag(name: "developers"), new EmailAddress("*****@*****.**") ); /* * =============== * STEP 3 * =============== * Execute your operation. * This returns a data type with two possible values. * Either<InfusioError, T> * =============== */ var result = await operation.RunWithLogs(client, List("Infusionsoft operations", "start")); result.Match( Left: error => Console.WriteLine($"error: {error.Value}"), Right: res => { res.Logs.Iter(Console.WriteLine); Console.WriteLine($"contact: {SerializeObject(res.Value, Indented)}"); } ); }
public async Task <AuthenticationResult> RefreshTokenAsync(RefreshTokenRequest request) { var validatedToken = GetPrincipalFromToken(request.Token); if (validatedToken == null) { return(new AuthenticationResult { Errors = new[] { "Invalid Token" } }); } var expiryDateUnix = long.Parse(validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Exp).Value); var expiryDateTimeUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) .AddSeconds(expiryDateUnix); if (expiryDateTimeUtc > DateTime.UtcNow) { return(new AuthenticationResult { Errors = new[] { "This token hasn't expired yet" } }); } var jti = validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Jti).Value; var storedRefreshToken = await _context.RefreshTokens.SingleOrDefaultAsync(x => x.Token == request.RefreshToken); if (storedRefreshToken == null) { return(new AuthenticationResult { Errors = new[] { "This refresh token does not exist" } }); } if (DateTime.UtcNow > storedRefreshToken.ExpiryDate) { return(new AuthenticationResult { Errors = new[] { "This refresh token has expired" } }); } if (storedRefreshToken.Invalidated) { return(new AuthenticationResult { Errors = new[] { "This refresh token has been invalidated" } }); } if (storedRefreshToken.Used) { return(new AuthenticationResult { Errors = new[] { "This refresh token has been used" } }); } if (storedRefreshToken.JwtId != jti) { return(new AuthenticationResult { Errors = new[] { "This refresh token does not match this JWT" } }); } storedRefreshToken.Used = true; _context.RefreshTokens.Update(storedRefreshToken); await _context.SaveChangesAsync(); var user = await _userManager.FindByIdAsync(validatedToken.Claims.Single(x => x.Type == "id").Value); return(await GenerateAuthenticationResultForUserAsync(user)); }
public async Task <IActionResult> Refresh([FromBody] RefreshTokenRequest request) { var authResponse = await _identityService.RefreshTokenAsync(request.Token, request.RefreshToken); return(IdentityResponse(authResponse)); }
public RefreshTokenResponse RefreshToken(RefreshTokenRequest _request, string token) { RefreshTokenResponse response = new RefreshTokenResponse(); CheckValidateTokenDTO validateDto = new CheckValidateTokenDTO { Audience = configuration["Audience"], Issuer = configuration["Issuer"], PrivateKey = configuration["PrivateKey"], IsValidateExpiry = false, Token = token }; var validatedToken = JWTHelper.CheckValidToken(validateDto); if (validatedToken.IsValid) { var tblRefreshToken = (from rt in db_Evoucher.TblRefreshToken where rt.RefreshToken == _request.RefreshToken && rt.UserId == validatedToken.UserID && rt.ExpiryDate > DateTime.Now select rt).FirstOrDefault(); if (tblRefreshToken != null && tblRefreshToken.RefreshToken != "") { GetGenerateTokenDTO getGenerateToken = new GetGenerateTokenDTO { Audience = configuration["Audience"], Issuer = configuration["Issuer"], PrivateKey = configuration["PrivateKey"], TokenExpiryMinute = Int32.Parse(configuration["TokenExpiryMinute"]), RefreshTokenExpiryMinute = Int32.Parse(configuration["RefreshTokenExpiryMinute"]), UserId = validatedToken.UserID, UserName = validatedToken.UserName }; var generatedToken = JWTHelper.GenerateToken(getGenerateToken); if (generatedToken != null && string.IsNullOrEmpty(generatedToken.ErrorStatus)) { response.AccessToken = generatedToken.AccessToken; response.AccessTokenExpireMinutes = generatedToken.TokenExpiresMinute; response.RefreshToken = generatedToken.RefreshToken; response.RefreshTokenExpireMinutes = Int32.Parse(configuration["RefreshTokenExpiryMinute"]); SaveRefreshToken(new SaveRefreshTokenDTO { ExpiryMinute = generatedToken.RefreshTokenExpiresMinute, RefreshToken = generatedToken.RefreshToken, UserId = generatedToken.UserId }); DeleteRefreshToken(_request.RefreshToken); } else { response.StatusCode = 500; response.ErrorType = "Token-Generation Fail."; response.ErrorMessage = "Unable to generate Access Token."; } DeleteExpiryRefreshToken(); db_Evoucher.SaveChanges(); } else { response.StatusCode = 401; response.ErrorType = "Unauthorized Request"; response.ErrorMessage = "Invalid or Expired Refresh Token."; } } else { response.StatusCode = 401; response.ErrorType = "Unauthorized Request"; response.ErrorMessage = "Invalid or Expired Access Token."; } return(response); }
public async Task <IActionResult> RefreshToken([FromBody] RefreshTokenRequest model) { return(_codeFactory.GetStatusCode(await _service.RefreshJwtToken(model))); }
public async Task <AuthenticationResult> VerifyAndGenerateTokenAsync(RefreshTokenRequest refreshTokenRequest) { try { var jwtTokenHandler = new JwtSecurityTokenHandler(); var tokenToBeVerified = jwtTokenHandler.ValidateToken(refreshTokenRequest.Token, _tokenValidationParameters, out var validatedToken); if (validatedToken is JwtSecurityToken jwtSecurityToken) { var isHmacSha256Encrypted = jwtSecurityToken.Header.Alg.Equals("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"); //var isHmacSha256Encrypted = jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, // StringComparison.InvariantCultureIgnoreCase); if (isHmacSha256Encrypted is false) { return(null); } var utcExpiryDate = long.Parse(tokenToBeVerified.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Exp).Value); var expiryDate = ConvertUnixTimeStampToDateTime(utcExpiryDate); if (expiryDate > DateTime.UtcNow) { return new AuthenticationResult { Success = false, Errors = new[] { "Token hasn't expired yet" } } } ; var persistedToken = await _appDbContext.RefreshTokens.FirstOrDefaultAsync(x => x.Token == refreshTokenRequest.RefreshToken); if (persistedToken is null) { return new AuthenticationResult { Success = false, Errors = new[] { "Token doesn't exist" } } } ; if (persistedToken.IsUsed) { return new AuthenticationResult { Success = false, Errors = new[] { "Token has been used" } } } ; if (persistedToken.IsInvalidated) { return new AuthenticationResult { Success = false, Errors = new[] { "Token has been invalidated" } } } ; var jti = tokenToBeVerified.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Jti).Value; if (persistedToken.JwtId != jti) { return new AuthenticationResult { Success = false, Errors = new[] { "Token doesn't match" } } } ; persistedToken.IsUsed = true; _appDbContext.RefreshTokens.Update(persistedToken); await _appDbContext.SaveChangesAsync(); var currentUser = await _userManager.FindByIdAsync(persistedToken.UserId); return(await GenerateAuthenticationResultAsync(currentUser)); } return(null); } catch (Exception exception) { return(null); } }
public async Task <IActionResult> RefreshTokenAsync(RefreshTokenRequest refreshTokenRequest) { return(Ok(await _authService.RefreshTokenAsync(refreshTokenRequest))); }
public ActionResult <RefreshTokenResponse> PostRefeshToken([FromRoute] string brand, [FromRoute] string provider, [FromBody] RefreshTokenRequest refreshToken) { return(new RefreshTokenResponse { AccessToken = "QWE", ExpiresIn = 12, RefreshToken = "ASD", Scope = "Scope", TokenType = "Barier" }); }
public Command(RefreshTokenRequest request) { this.Model = request; }
public async Task <ActionResult> RefreshTokenAsync([FromBody] RefreshTokenRequest refreshTokenDto) { if (refreshTokenDto == null) { return(this.BadRequest()); } // Still validate the passed in token, but ignore its expiration date by setting validate lifetime to false var validationParameters = new TokenValidationParameters { ClockSkew = TimeSpan.Zero, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(this.authSettings.APISecrect)), RequireSignedTokens = true, ValidateIssuer = true, ValidateAudience = true, RequireExpirationTime = true, ValidateLifetime = false, ValidAudience = this.authSettings.TokenAudience, ValidIssuer = this.authSettings.TokenIssuer }; ClaimsPrincipal tokenClaims; try { tokenClaims = new JwtSecurityTokenHandler().ValidateToken(refreshTokenDto.Token, validationParameters, out var rawValidatedToken); } catch (Exception e) { return(this.Unauthorized(e.Message)); } var userIdClaim = tokenClaims.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim == null || !int.TryParse(userIdClaim, out var userId)) { return(this.Unauthorized("Invalid token.")); } var user = await this.userRepository.GetByIdAsync(userId, user => user.RefreshTokens); if (user == null) { return(this.Unauthorized("Invalid token.")); } user.RefreshTokens.RemoveAll(token => token.Expiration <= DateTime.UtcNow); var currentRefreshToken = user.RefreshTokens.FirstOrDefault(token => token.DeviceId == refreshTokenDto.DeviceId && token.Token == refreshTokenDto.RefreshToken); if (currentRefreshToken == null) { await this.userRepository.SaveAllAsync(); return(this.Unauthorized("Invalid token.")); } user.RefreshTokens.Remove(currentRefreshToken); var token = this.GenerateJwtToken(user); var refreshToken = GenerateRefreshToken(); user.RefreshTokens.Add(new RefreshToken { Token = refreshToken, Expiration = DateTimeOffset.UtcNow.AddMinutes(this.authSettings.RefreshTokenExpirationTimeInMinutes), DeviceId = refreshTokenDto.DeviceId }); await this.userRepository.SaveAllAsync(); return(this.Ok(new { token, refreshToken })); }
public async Task <IActionResult> RefreshToken([FromBody] RefreshTokenRequest request) { var result = await _authService.RefreshTokenAsync(request.RefreshToken, request.AccessToken); return(GenerateResponse(result)); }
public async Task <ActionResult <TokenResponse> > RefreshTokenAsync([FromBody] RefreshTokenRequest request) { return(await Mediator.Send(request)); }
/// <summary> /// Refreshes the access token. /// </summary> /// <remarks> /// Called when the access token has expired. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// </param> public static TokenResponse RefreshToken(this IPlatformEndpoints operations, RefreshTokenRequest body = default(RefreshTokenRequest)) { return(operations.RefreshTokenAsync(body).GetAwaiter().GetResult()); }
public ActionResult <AuthenticateResponse> RefreshToken(RefreshTokenRequest refreshToken) { var response = accountService.RefreshToken(refreshToken.RefreshToken); return(Ok(response)); }
/// <summary> /// Refreshes the access token. /// </summary> /// <remarks> /// Called when the access token has expired. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <TokenResponse> RefreshTokenAsync(this IPlatformEndpoints operations, RefreshTokenRequest body = default(RefreshTokenRequest), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RefreshTokenWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public async Task <AuthResponse> RefreshToken([FromBody] RefreshTokenRequest request) { return(await _tokenService.RefreshTokenAsync(request.RefreshToken)); }
public override async Task <UserCredentialsReply> RefreshToken(RefreshTokenRequest request, ServerCallContext context) { return(await _authorization.Refresh(request.Token)); }
public async Task <ActionResult> Refresh([FromBody] RefreshTokenRequest model) { var response = await _identityService.GetRefreshTokenAsync(model); return(Ok(response)); }
public async Task <LoginResponse> RefreshToken(RefreshTokenRequest request) { return(await _authService.RefreshToken(request)); }
public async Task <IActionResult> RefreshToken([FromBody] RefreshTokenRequest request) { return(await ExecuteServiceAsync(() => _userService.RefreshTokenAsync(request))); }
public Task <AccessTokenResponse> GetTokenAsync(RefreshTokenRequest request, CancellationToken cancellationToken = default) { return(_getToken(request, cancellationToken)); }
public Task <AccessTokenResponse> GetTokenAsync(RefreshTokenRequest request) { return(_getToken(request)); }
public async Task <ActionResult> RefreshToken([FromBody] RefreshTokenRequest request) { JwtAuthentificationResponse response = await _userService.RefreshToken(request); return(Ok(response)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var clientId = "mvc"; var clientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0"; var authority = "https://localhost:5443"; services.AddTransient <HttpClient>() .AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies", options => { var pendingRefreshTokenRequests = new ConcurrentDictionary <string, bool>(); var events = options.Events; events.OnValidatePrincipal = async context => { var tokens = context.Properties.GetTokens(); var services = context.HttpContext.RequestServices; var logger = services.GetRequiredService <ILogger <Startup> >(); if (tokens == null || !tokens.Any()) { logger.LogDebug("No tokens found."); return; } var refreshToken = tokens.FirstOrDefault(t => t.Name == OpenIdConnectParameterNames.RefreshToken); if (refreshToken == null) { logger.LogWarning("Refresh token not found."); return; } var expiresAt = tokens.FirstOrDefault(t => t.Name == "expires_at"); if (expiresAt == null) { logger.LogWarning("expires_at not found."); return; } var expires = DateTimeOffset.Parse(expiresAt.Value, CultureInfo.InvariantCulture); logger.LogInformation("Token expire at {ExpireAtt}", expires); expires = expires.AddSeconds(-15); if (expires > DateTimeOffset.UtcNow) { logger.LogDebug("No need to refresh"); return; } if (!pendingRefreshTokenRequests.TryAdd(refreshToken.Value, true)) { logger.LogInformation("Pending refresh the token {RefreshToken}", refreshToken.Value); return; } try { var httpClient = services.GetRequiredService <HttpClient>(); using var request = new RefreshTokenRequest { Address = $"{authority}/connect/token", ClientId = clientId, ClientSecret = clientSecret, RefreshToken = refreshToken.Value }; var response = await httpClient.RequestRefreshTokenAsync(request); if (response.IsError) { logger.LogWarning("Error refreshing token: {error}", response.Error); context.RejectPrincipal(); return; } context.Properties.UpdateTokenValue("access_token", response.AccessToken); context.Properties.UpdateTokenValue("refresh_token", response.RefreshToken); expires = DateTimeOffset.UtcNow.AddSeconds(response.ExpiresIn); context.Properties.UpdateTokenValue("expires_at", expires.ToString("o", CultureInfo.InvariantCulture)); await context.HttpContext.SignInAsync(context.Principal, context.Properties); logger.LogInformation("Automatic refresh token succeed. Next expire date {ExpireAt}", expires); } catch (Exception e) { logger.LogError(e.Message, e); } finally { pendingRefreshTokenRequests.TryRemove(refreshToken.Value, out _); } }; }) .AddOpenIdConnect("oidc", options => { options.Authority = authority; options.RequireHttpsMetadata = false; options.ClientId = clientId; options.ClientSecret = clientSecret; options.ResponseType = "code id_token"; options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("api1"); options.Scope.Add("offline_access"); options.GetClaimsFromUserInfoEndpoint = true; options.SaveTokens = true; }); services.AddControllersWithViews(); }
internal static Task<Tokenizer> RequestRefreshTokenAsync(this IRestClient client, RefreshTokenRequest tokenRequest, CancellationToken cancellationToken = default) { return ExecuteAsync(client, tokenRequest, tokenRequest.GrantType, cancellationToken); }
public async Task <IActionResult> RefreshToken(RefreshTokenRequest command) { var token = await _authService.RefreshToken(command.Index, command.RefreshToken); return(Ok(token)); }
public async Task <IActionResult> RefreshToken(RefreshTokenRequest requestData) { var responseData = await _jwtTokenService.RefreshToken(requestData.Token, requestData.RefreshToken); return(Ok(responseData)); }