如何知道访问令牌已过期?
How to know that access token has expired?
客户端如何知道访问令牌已过期,以便他使用刷新令牌请求另一个访问令牌?
如果答案是服务器 API 将 return 401,那么 API 如何知道访问令牌已过期?
我正在使用 IdentityServer4。
如果包含的不记名令牌已经过期,您的 api 应该拒绝任何呼叫。对于 Webapi 应用程序,IdentityServerAuthenticationOptions
将完成工作。
但是您的调用者 Web 应用程序负责保持您的 access_token 活动。例如,如果您的 Web 应用程序是 ASP.Net 核心应用程序,您可以使用 AspNetCore.Authentication.Cookies
来验证任何请求。在这种情况下,您可以通过 OnValidatePrincipal
事件找到有关令牌过期信息的信息。
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
//ExpireTimeSpan = TimeSpan.FromSeconds(100),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = async x =>
{
if (x.Properties?.Items[".Token.expires_at"] == null) return;
var now = DateTimeOffset.UtcNow;
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
if (timeElapsed > timeRemaining)
{
//Get the new token Refresh the token
}
}
}
}
我在另一个
中添加了关于如何使用刷新令牌获取新访问令牌的完整实现
客户端如何知道访问令牌已过期,以便他使用刷新令牌请求另一个访问令牌?
如果答案是服务器 API 将 return 401,那么 API 如何知道访问令牌已过期?
我正在使用 IdentityServer4。
如果包含的不记名令牌已经过期,您的 api 应该拒绝任何呼叫。对于 Webapi 应用程序,IdentityServerAuthenticationOptions
将完成工作。
但是您的调用者 Web 应用程序负责保持您的 access_token 活动。例如,如果您的 Web 应用程序是 ASP.Net 核心应用程序,您可以使用 AspNetCore.Authentication.Cookies
来验证任何请求。在这种情况下,您可以通过 OnValidatePrincipal
事件找到有关令牌过期信息的信息。
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
//ExpireTimeSpan = TimeSpan.FromSeconds(100),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = async x =>
{
if (x.Properties?.Items[".Token.expires_at"] == null) return;
var now = DateTimeOffset.UtcNow;
var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
if (timeElapsed > timeRemaining)
{
//Get the new token Refresh the token
}
}
}
}
我在另一个