我正在尝试在我的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。
答案 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")
}
希望这个满足您的需求。快乐编码:)