在iOS 6上使用AFOAuth2Client和AFNetworking我能够获取访问令牌,但无法访问资源,服务器响应401未经授权的状态代码。这是针对使用门卫作为OAuth提供者的自定义Rails 3 API后端。下面的客户端Ruby代码,使用的OAuth2宝石,工程确定:AFOAuth2Client无法访问资源
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的正确方法吗?任何想法为什么这不起作用?
看看在https://github.com/AFNetworking/AFOAuth2Client/blob/master/AFOAuth2Client/AFOAuth2Client.h文件。顶部有一个注释,建议您不要将它用作基类。 – davidbitton