在 iOS 6 上使用 AFOAuth2Client 和 AFNetworking 我可以获得访问令牌,但无法访问资源,服务器以 401 未授权状态代码响应。这是针对使用门卫作为 OAuth 提供者的自定义 Rails 3 API 后端。以下客户端 ruby 代码使用 OAuth2 gem,可以正常工作:
client = OAuth2::Client.new(app_id, secret, site: "http://subdomain.example.com/")
access_token = client.password.get_token('username', 'password')
access_token.get('/api/1/products').parsed
iOS 代码如下,在登录按钮处理程序中,我使用用户名和密码进行身份验证,并存储凭据:
- (IBAction)login:(id)sender {
NSString *username = [usernameField text];
NSString *password = [passwordField text];
NSURL *url = [NSURL URLWithString:kClientBaseURL];
AFOAuth2Client *client = [AFOAuth2Client clientWithBaseURL:url clientID:kClientID secret:kClientSecret];
[client authenticateUsingOAuthWithPath:@"oauth/token"
username:username
password:password
scope:nil
success:^(AFOAuthCredential *credential) {
NSLog(@"Successfully received OAuth credentials %@", credential.accessToken);
[AFOAuthCredential storeCredential:credential
withIdentifier:client.serviceProviderIdentifier];
[self performSegueWithIdentifier:@"LoginSegue" sender:sender];
}
failure:^(NSError *error) {
NSLog(@"Error: %@", error);
[passwordField setText:@""];
}];
}
我已经AFHTTPClient
为我的端点进行了子类化,并在initWithBaseURL
其中检索凭据并使用访问令牌设置授权标头:
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:@"subdomain.example.com"];
[self setAuthorizationHeaderWithToken:credential.accessToken];
return self;
}
这是使用 AFOAuth2Client 和 AFNetworking 的正确方法吗?知道为什么这不起作用吗?