AFOAuth2Client 是 AFNetworking 的扩展,极大简化了与 OAuth 2 提供程序进行认证的过程。
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFOAuth2Client *OAuth2Client = [AFOAuth2Client clientWithBaseURL:baseURL
clientID:kClientID
secret:kClientSecret];
[OAuth2Client authenticateUsingOAuthWithPath:@"/oauth/token"
username:@"username"
password:@"password"
scope:@"email"
success:^(AFOAuthCredential *credential) {
NSLog(@"Token: %@", credential.accessToken);
}
failure:^(NSError *error) {
NSLog(@"Error: %@", error);
}];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:baseURL];
[client setDefaultHeader:@"Authorization"
value:[NSString stringWithFormat:@"Bearer %@", credential.accessToken]];
[client getPath:@"/path/to/protected/resource"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
[AFOAuthCredential storeCredential:credential
withIdentifier:serviceProviderIdentifier];
AFOAuthCredential *credential =
[AFOAuthCredential retrieveCredentialWithIdentifier:serviceProviderIdentifier];
AFOAuth2Client 所有版本的文档可在 CocoaDocs 上找到。
Mattt Thompson
AFOAuth2Client 在 MIT 许可证下提供。有关更多信息,请参阅 LICENSE 文件。