我面临的问题是我的 JWT 在空闲后几分钟内到期,即使我已将 ExpireTimeSpan 设置为 60 分钟(或更长;甚至尝试了 1 年)。
目前我防止令牌过期的方式是每隔几分钟向我的服务器发送虚拟请求,这实际上会触发 SlidingExpiration 部分。
理想情况下,即使在用户关闭我的网页后,我也希望令牌保持活动状态。我不确定我在启动代码中遗漏了什么,有什么指示吗?
services.AddAuthentication(a =>
{
a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
a.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
string secretKeyStr = Configuration.GetValue<string>("SecretKey");
byte[] secretKey = null;
if (secretKeyStr != null)
secretKey = Encoding.ASCII.GetBytes(secretKeyStr);
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(secretKey),
ValidateIssuer = false,// validate the server that generates the token
ValidateAudience = false,//validate the user who generates token is authorized
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromDays(1),
};
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.ExpireTimeSpan = TimeSpan.FromMinutes(60); });
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.IsEssential = true;
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.Cookie.HttpOnly = true;
});
services.ConfigureApplicationCookie(options =>
{
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
});
编辑:这是我生成令牌的方式。
var JWToken = new JwtSecurityToken(
issuer: Configuration.GetValue<string>("my_issuer"),
audience: Configuration.GetValue<string>("my_audience"),
claims: GetUserClaims(user),
notBefore: new DateTimeOffset(DateTime.Now).DateTime,
expires: DateTime.UtcNow.AddYears(1),
//Using HS256 Algorithm to encrypt Token
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(secretKey),
SecurityAlgorithms.HmacSha256Signature)
);
var token = new JwtSecurityTokenHandler().WriteToken(JWToken);