Browse Source

Check token expiration.

We need to refresh the current user(`ThreadCurrentPrincipal`)
pull/16504/head
maliming 3 years ago
parent
commit
bceae5ba3a
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 31
      framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/CookieAuthenticationOptionsExtensions.cs
  2. 3
      templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/MyProjectNameWebModule.cs

31
framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/CookieAuthenticationOptionsExtensions.cs

@ -0,0 +1,31 @@
using System;
using System.Globalization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
namespace Microsoft.Extensions.DependencyInjection;
public static class CookieAuthenticationOptionsExtensions
{
public static CookieAuthenticationOptions CheckTokenExpiration(this CookieAuthenticationOptions options, TimeSpan? advance = null)
{
advance ??= TimeSpan.FromMinutes(5);
var originalHandler = options.Events.OnValidatePrincipal;
options.Events.OnValidatePrincipal = async principalContext =>
{
originalHandler?.Invoke(principalContext);
if (principalContext.Principal != null && principalContext.Principal.Identity != null && principalContext.Principal.Identity.IsAuthenticated)
{
var tokenExpiresAt = principalContext.Properties.Items[".Token.expires_at"];
if (tokenExpiresAt != null &&
DateTimeOffset.TryParseExact(tokenExpiresAt, "o", null, DateTimeStyles.RoundtripKind, out var expiresAt) &&
expiresAt < DateTimeOffset.UtcNow.Subtract(advance.Value))
{
principalContext.RejectPrincipal();
await principalContext.HttpContext.SignOutAsync(principalContext.Scheme.Name);
}
}
};
return options;
}
}

3
templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/MyProjectNameWebModule.cs

@ -145,6 +145,7 @@ public class MyProjectNameWebModule : AbpModule
.AddCookie("Cookies", options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(365);
options.CheckTokenExpiration();
})
.AddAbpOpenIdConnect("oidc", options =>
{
@ -232,7 +233,7 @@ public class MyProjectNameWebModule : AbpModule
dataProtectionBuilder.PersistKeysToStackExchangeRedis(redis, "MyProjectName-Protection-Keys");
}
}
private void ConfigureDistributedLocking(
ServiceConfigurationContext context,
IConfiguration configuration)

Loading…
Cancel
Save