3

我正在尝试在我的 iphone 应用程序中实现 Oauth 身份验证。

设想

创建 AFOAuth2Client 的子类并覆盖该方法

- (void)authenticateWithUsernameAndPassword:(NSString *)username
                                   password:(NSString *)password
                                    success:(void (^)(AFOAuthCredential *credential))success
                                    failure:(void (^)(NSError *error))failure;

进行身份验证并将身份验证令牌设置为客户端中的标头,并使用其 sharedInstance 调用 Web 服务(使用 Restkit)。

问题 我不能做的是关于刷新令牌。我有获取刷新令牌的 api。

  1. 我的应用程序如何知道令牌已过期?
  2. 在哪里检查令牌过期并调用以获取新的刷新令牌
  3. AFOAuth2Client 中有一个选项可以做到吗?
4

1 回答 1

2
- (NSURLSessionTask *)authenticateUsingOAuthWithURLString:(NSString *)URLString 
                               refreshToken:(NSString *)refreshToken
                               success:(void (^)(AFOAuthCredential *credential))success
                               failure:(void (^)(NSError *error))failure;

使用此方法,您可以向身份验证服务器提供新的 refreshToken。在此之前,您需要在用户默认值中将 AFOAuthCredential保存为 NSData,然后在调用 api 时检索 AFOAuthCredential 并使用此方法检查它是否已过期。

func refreshTokenIfUnavailable(completionHandler : @escaping(_ finished:Bool,_ error:Error) -> ()) {
    let credentialData = UserDefaults.standard.object(forKey: CREDENTIAL) as? NSData

    if let credentialData = credentialData {
        let credential = NSKeyedUnarchiver.unarchiveObject(with: credentialData as Data) as? AFOAuthCredential

        if let _ = credential
        {
            if credential!.isExpired {
                let urlString = OAUTH_BASE_URL
                let url = URL(string: urlString)
                let oAuthManager = AFOAuth2Manager(baseURL: url!, clientID: YOUR_AUTH_CLIENT_ID secret: YOUR_AUTH_SECRET_ID)
                oAuthManager.authenticateUsingOAuth(withURLString: "oauth/token", refreshToken: (credential?.refreshToken)!, success: { (credential) in
                    self.saveAccessToken(credential: credential)
                    completionHandler(true,YOUR_ERROR))
                }, failure: { (error) in
                    completionHandler((credential != nil),NSError(domain: "", code: 204, userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]))
                })
            }
            completionHandler((credential != nil),YOUR_ERROR_MESSAGE))
        }
    }
}

func saveAccessToken(credential : AFOAuthCredential) {

    KeychainService.saveAccessToken(service: ACCESS_TOKEN as NSString, data: credential.accessToken as NSString)

    let credentialData = NSKeyedArchiver.archivedData(withRootObject: credential)
    let userDefaults = UserDefaults.standard
    userDefaults.set(credentialData, forKey: "credentials")
}

希望这个能满足你的需要。快乐编码:)

于 2018-03-23T11:01:24.257 回答