5

在 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 的正确方法吗?知道为什么这不起作用吗?

4

1 回答 1

5

设法通过改变来实现这个工作:

    AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:@"subdomain.example.com"];
    [self setAuthorizationHeaderWithToken:credential.accessToken];

至:

    AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:@"subdomain.example.com"];
    NSString *authValue = [NSString stringWithFormat:@"Bearer %@", credential.accessToken];
    [self setDefaultHeader:@"Authorization" value:authValue];

更新

我没有注意到的是它AFOAuth2Client本身就是一个子类,AFHTTPClient因此可以用作 API 类的基类,例如:

@interface YFExampleAPIClient : AFOAuth2Client

    + (YFExampleAPIClient *)sharedClient;

    /**

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

    @end

实现变为:

@implementation YFExampleAPIClient

+ (YFExampleAPIClient *)sharedClient {
    static YFExampleAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURL *url = [NSURL URLWithString:kClientBaseURL];
        _sharedClient = [YFExampleAPIClient clientWithBaseURL:url clientID:kClientID secret:kClientSecret];
    });

    return _sharedClient;
}

- (void)authenticateWithUsernameAndPassword:(NSString *)username
                                   password:(NSString *)password
                                    success:(void (^)(AFOAuthCredential *credential))success
                                    failure:(void (^)(NSError *error))failure {
    [self authenticateUsingOAuthWithPath:@"oauth/token"
                                  username:username
                                  password:password
                                     scope:nil
                                   success:^(AFOAuthCredential *credential) {
                                       NSLog(@"Successfully received OAuth credentials %@", credential.accessToken);
                                       [self setAuthorizationHeaderWithCredential:credential];
                                       success(credential);
                                   }
                                   failure:^(NSError *error) {
                                       NSLog(@"Error: %@", error);
                                       failure(error);
                                   }];
}

- (id)initWithBaseURL:(NSURL *)url
             clientID:(NSString *)clientID
               secret:(NSString *)secret {
    self = [super initWithBaseURL:url clientID:clientID secret:secret];
    if (!self) {
        return nil;
    }

    [self setDefaultHeader:@"Accept" value:@"application/json"];

    return self;
}

@end

请注意,它initWithBaseURL被覆盖以设置 HTTP 接受标头。

GitHub 上提供了完整的源代码 - https://github.com/yellowfeather/rails-saas-ios

于 2013-01-06T10:23:14.730 回答