diff --git a/src/Server/Program.cs b/src/Server/Program.cs index 84ff262..72662b8 100755 --- a/src/Server/Program.cs +++ b/src/Server/Program.cs @@ -111,6 +111,7 @@ using (HttpClient client = new HttpClient()) { Console.WriteLine("PublicKey loaded"); } +// Pull JWT out of cookie for auth builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; @@ -197,28 +198,34 @@ app.UseRouting(); app.UseAuthentication(); +// Autorenew JWT about to expire app.Use(async (context, next) =>{ ClaimsPrincipal user = context.User; if (user.Identity?.IsAuthenticated == true) { string? token = context.Request.Cookies["mistox_session"]; - Claim? expClaim = user.FindFirst(JwtRegisteredClaimNames.Exp); - if (expClaim != null && long.TryParse(expClaim.Value, out long expUnix)) { - DateTimeOffset expTime = DateTimeOffset.FromUnixTimeSeconds(expUnix); - if ((expTime - DateTimeOffset.UtcNow) < TimeSpan.FromDays(3)) { - using (HttpClient client = new HttpClient()) { - HttpResponseMessage response = await client.PostAsJsonAsync("https://auth.mistox.com/api/auth/renew", new JWTRenewRequest() { JWT = token }); - if (response.IsSuccessStatusCode) { - string newJwt = await response.Content.ReadAsStringAsync(); - context.Response.Cookies.Append("mistox_session", newJwt, new CookieOptions { - HttpOnly = true, - Secure = true, - SameSite = SameSiteMode.Strict, - Expires = DateTimeOffset.UtcNow.AddYears(3) - }); + Claim? staySignedIn = user.FindFirst(ClaimTypes.IsPersistent); + if (staySignedIn != null && bool.TryParse(staySignedIn.Value, out bool sli) && sli == true) { + Claim? expClaim = user.FindFirst(ClaimTypes.Expiration); + if (expClaim != null && long.TryParse(expClaim.Value, out long expUnix)) { + DateTimeOffset expTime = DateTimeOffset.FromUnixTimeSeconds(expUnix); + if ((expTime - DateTimeOffset.UtcNow) < TimeSpan.FromDays(3)) { + using (HttpClient client = new HttpClient()) { + HttpResponseMessage response = await client.PostAsJsonAsync("https://auth.mistox.com/api/auth/renew", new JWTRenewRequest() { JWT = token }); + if (response.IsSuccessStatusCode) { + string newJwt = await response.Content.ReadAsStringAsync(); + context.Response.Cookies.Append("mistox_session", newJwt, new CookieOptions { + HttpOnly = true, + Secure = true, + SameSite = SameSiteMode.Strict, + Expires = DateTimeOffset.UtcNow.AddYears(3) + }); + } } } } } + } else { + context.Response.Cookies.Delete("mistox_session"); } await next();