【问题标题】:Refresh JWT authentication token on ios在 ios 上刷新 JWT 身份验证令牌
【发布时间】:2017-12-29 19:34:17
【问题描述】:

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

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

任何帮助将不胜感激

【问题讨论】:

  • 你找到正确的方法了吗?

标签: ios swift oauth jwt


【解决方案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()
        }
    }
}

最后,在您的AppDelegatedidFinishLaunchingwillEnterForegrounddidEnterBackground 中,执行以下操作

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //Your code here
    NotificationCenter.default.addObserver(self, selector: #selector(postTokenAcquisitionScript), name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}

func applicationWillEnterForeground(_ application: UIApplication) {
    //Your code here
    NotificationCenter.default.addObserver(self, selector: #selector(postTokenAcquisitionScript), name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}

func applicationDidEnterBackground(_ application: UIApplication) {
    //Your code here
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 2019-02-27
    • 1970-01-01
    • 2017-11-08
    • 2021-03-05
    • 2019-08-30
    • 2021-09-25
    • 2015-06-24
    • 2021-09-17
    相关资源
    最近更新 更多