根据发布的时间检查令牌到期并在

时间:2018-03-14 16:44:55

标签: datetime f#

检查第三方API调用的令牌到期时间的正确方法。

Token.fs

type Token = {
    mutable access_token: string;
    mutable expires_in: string;
    mutable issued_at: System.DateTime;
}

我添加了一个字段issued_at来跟踪令牌的发布时间,并根据expires_in值计算到期时间。

我从API获得的{p> expires_in值是86399984(以毫秒为单位),大约是24小时。我如何处理到期管理,以下是我的尝试。

let token = {access_token = ""; expires_in = ""; issued_at = ""}
api电话后

token.access_token <- result.access_token
token.issued_at <- DateTime.Now
token.expires_in <- result.expires_in // 86399984 (ms) ~ 24 hours

现在稍后当我想要在我请求另一个令牌之前检查令牌是否已过期时,我应该如何处理它?我想根据issued_at - 给定expires_in进行检查,而不是24小时进行硬编码,因为它可能会发生变化。

修改

重构Token以更好地解决问题。放弃上面的代码。

type Token = {
    mutable access_token: string;
    mutable expires_at: DateTime; // introducing a new field
}



let private credentials = {clientId = ""; clientSecret = ""; token = {access_token = ""; expires_at = DateTime.Now}}

let requestToken (claims: Credentials) =

    if credentials.token.expires_at < DateTime.Now then
         // call REST api
         let output = reader.ReadToEnd()

        let result = JsonConvert.DeserializeObject<Token>(output)      
        credentials.token.access_token <- result.access_token
        credentials.token.expires_at <- DateTime.Now + TimeSpan(0, 0, (int(result.expires_in))) // expires_in -> 86399984 (ms) ~ 24 hours
        credentials // return renewed token
      else
         credentials // return cached value

0 个答案:

没有答案