2013-01-05 14 views
5

iOS'ta AFOAuth2Client ve AFNetworking'i kullanma 6 Erişim belirteci alabiliyorum, ancak bir kaynağa erişemiyorum, sunucu 401 yetkisiz durum koduyla yanıt veriyor. Bu, OAuth sağlayıcısı olarak görev yapan bir özel Rails 3 API arka ucuna aykırıdır. aşağıdaki istemci yakut kodu, OAuth2 gem kullanarak, Tamam çalışır:AFOAuth2Client kaynağına erişemiyor

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 kod giriş düğmesi işleyicisinde ben kullanıcı adı ve şifreyi kullanarak kimlik doğrulaması ve kimlik bilgilerini depolamak, aşağıdaki gibidir:

- (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:@""]; 
           }]; 
} 

ve benim son nokta için AFHTTPClient sınıflandırma ettik ve initWithBaseURL o kimlik bilgilerini alır ve erişim belirteci ile yetkilendirme başlığını ayarlar:

- (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 ve AFNetworking'i kullanmanın doğru yolu bu mu? Ve bunun neden çalışmadığı hakkında bir fikrin var mı?

cevap

5

değiştirerek bu çalışma almak için Yönetilen:

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

için: Ben AFOAuth2ClientAFHTTPClient bir alt sınıfı kendisini bu kadar olabilir olduğunu olduğunu fark başarısız olmuştu ne

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

GÜNCELLEME

API sınıfının temel sınıfı olarak kullanılabilir, örneğin:

@interface YFExampleAPIClient : AFOAuth2Client 

    + (YFExampleAPIClient *)sharedClient; 

    /** 

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

    @end 

Ve uygulama haline gelir: initWithBaseURL HTTP başlığı kabul ayarlamak için geçersiz kılınır

@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 

Not söyledi.

Tam kaynak kodu GitHub'dan mevcuttur -

+1

https://github.com/yellowfeather/rails-saas-ios https://github.com/AFNetworking/AFOAuth2Client/blob/master/AFOAuth2Client/AFOAuth2Client.h dosyasına bir göz atın. Üstte, bunu temel sınıfınız olarak kullanmamanızın önerildiği bir not vardır. – davidbitton

İlgili konular