2017-09-08 534 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

獲得新的訪問令牌全面實施