处理访问令牌的过期时间



我正在MVC项目中使用一些web API方法。我正在做的是创建一个API处理类。我计划在这个类的构造函数中获取访问令牌,然后再次将其附加到构造函数中的webapihandler对象。然后我将使用几个API调用,这很好。然而,我认为我必须在每次调用之前控制令牌的过期时间,如果它过期了,那么我必须创建一个。我不知道如何检查代币的到期时间。

这是我第一次以这种方式处理代币,我们非常感谢您的帮助。

您希望在数据库中保存access_token、refresh_token,token_expire_time和last_write。lastwrite是创建访问令牌的时间,tokenexpiretime应该是访问令牌到期前的时间,以分钟或秒为单位。

从那里,您只需将(last_write时间+token_expire_time(与现在的时间进行比较。

请记住,在比较和保存数据库或时区中的时间时,请始终使用DateTime.UtcNow,否则将无法正常刷新。

以下是的示例

数据库类

public class Token
{
public int Id { get; set; }
public string AccessToken { get; set; }
public string RefreshToken { get; set; }
public DateTime LastWrite { get; set; }
public int Expiration { get; set; }
}

检查刷新的功能:

// call this to get the token before making API call
public static async Task<string> GetAccessToken(Token token)
{
string accessToken;
if (token.LastWrite.AddSeconds(token.Expiration) <= DateTime.UtcNow)
{
// refresh and update the database with the new tokens/expiration
}
else
{
accessToken = token.AccessToken;
}
return accessToken;
}

最新更新