每小时运行OAuth URLRequest? - 斯威夫特

时间:2021-12-20 01:09:51

I am using an API in my iOS application that only allows a user to have an OAuth access token for an hour. How would I go about getting a new access token every hour? Would I set a TimeInterval or how would I be able to check if the access token is expired?

我在我的iOS应用程序中使用API​​,它只允许用户拥有一小时的OAuth访问令牌。我如何每小时获得一个新的访问令牌?我会设置一个TimeInterval,或者我如何能够检查访问令牌是否已过期?

Here is how I retrieve my access token with Alamofire. And I do not need a refresh token as mobile apps do not get them.

以下是我使用Alamofire检索访问令牌的方法。而且我不需要刷新令牌,因为移动应用程序无法获取它们。

guard let url = URL(string: "https://www.reddit.com/api/v1/access_token") else { return }
            let uuid = UUID().uuidString
            let params: Parameters = [
                "grant_type" : "https://oauth.reddit.com/grants/installed_client",
                "device_id" : "\(uuid)"]


            let username = "MY_CLIENT_ID"
            let password = ""
            let loginString = String(format: "%@:%@", username, password)
            let loginData = loginString.data(using: String.Encoding.utf8)! as NSData
            let base64EncodedString = loginData.base64EncodedString()

            let headers = ["Content-Type" : "application/x-www-form-urlencoded",
                           "Authorization" : "Basic \(base64EncodedString)"]

            Alamofire.request(url, method: .post , parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response) in

                UserDefaults.standard.set(uuid, forKey: "userID")
                UserDefaults.standard.synchronize()
                if let JSON = response.result.value as? [String:Any] {
                    guard let accessToken = JSON["access_token"] as? String else { return }
                    KeychainWrapper.standard.set(accessToken, forKey: "oauthToken")
                }

1 个解决方案

#1


0  

Easiest way is to check if token is valid when doing api call and authenticate it again if it is about to expire. You can decode token using JWTDecode library. -> JWTDecode

最简单的方法是在执行api调用时检查令牌是否有效,如果它即将到期则再次验证它。您可以使用JWTDecode库解码令牌。 - > JWTDecode

You can debug print Your token and try to see what informations You get inside using this website https://jwt.io

您可以调试打印您的令牌,并尝试使用此网站https://jwt.io查看您的内容

#1


0  

Easiest way is to check if token is valid when doing api call and authenticate it again if it is about to expire. You can decode token using JWTDecode library. -> JWTDecode

最简单的方法是在执行api调用时检查令牌是否有效,如果它即将到期则再次验证它。您可以使用JWTDecode库解码令牌。 - > JWTDecode

You can debug print Your token and try to see what informations You get inside using this website https://jwt.io

您可以调试打印您的令牌,并尝试使用此网站https://jwt.io查看您的内容