如何实现AFOAuth2Client来获取刷新令牌?

时间:2013-01-30 05:05:59

标签: ios ipad oauth-2.0 restkit afnetworking

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

方案

创建AFOAuth2Client的子类并覆盖方法

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

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

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

  1. 我的应用如何知道令牌已过期?
  2. 检查令牌已过期的位置并致电以获取新的刷新令牌
  3. AFOAuth2Client中是否有选项可以执行此操作?

1 个答案:

答案 0 :(得分:2)

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

使用此方法,您可以向auth Server提供新的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")
}

希望这个满足您的需求。快乐编码:)