【问题标题】:How to know that access token has expired?如何知道访问令牌已过期?
【发布时间】:2018-02-17 07:11:14
【问题描述】:

客户端如何知道访问令牌已过期,以便他使用刷新令牌请求另一个访问令牌?

如果回答是服务端 API 会返回 401,那么 API 怎么知道访问令牌已经过期?

我正在使用 IdentityServer4。

【问题讨论】:

    标签: access-token identityserver4


    【解决方案1】:

    如果包含的不记名令牌已经过期,您的 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
                }
            }
        }
    }
    

    我在另一个 StackOverflow answer 中添加了有关如何使用刷新令牌获取新访问令牌的完整实现

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 2014-05-13
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 2012-02-15
      • 2016-06-04
      相关资源
      最近更新 更多