在ios上刷新JWT身份验证令牌

时间:2017-07-24 09:22:55

标签: ios swift oauth jwt

我正在使用JWT身份验证处理应用程序。服务器端在expiry date之后没有为自动更新令牌提供机制,但我已经为刷新令牌提供了一种特殊方法。

实际上我不知道如何正确检查expiry date。我考虑为Timer设置expiry date,但当应用在后台时,计时器不起作用。我还考虑在viewWillAppear中检查令牌有效性,但通过这样做,服务器请求的数量急剧增加,这也不够好。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

首先,您应该在AppDelegate中创建一个处理令牌获取的方法。然后做这样的事情

func getToken() {
    //Whatever you need to do here.
    UserDefaults.standard.set(Date(), forKey: "tokenAcquisitionTime")
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}

AppDelegate

中创建一个计时器变量
var timer: Timer!

AppDelegate

中创建以下方法
func postTokenAcquisitionScript() {
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
}

func tick() {
    if let time = UserDefaults.standard.value(forKey: "tokenAcquisitionTime") as? Date {
        if Date().timeIntervalSince(time) > 3600 { //You can change '3600' to your desired value. Keep in mind that this value is in seconds. So in this case, it is checking for an hour
            timer.invalidate()
            getToken()
        }
    }
}

最后,在AppDelegate的{​​{1}},didFinishLaunchingwillEnterForeground中,执行以下操作

didEnterBackground