2017-09-08 532 views
0

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

如果答案是服务器API将返回401,那么API如何知道访问令牌已过期?

我正在使用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

获得新的访问令牌全面实施