Note that there are some explanatory texts on larger screens.

plurals
  1. POAFOAuth2Client unable to access resource
    text
    copied!<p>Using AFOAuth2Client and AFNetworking on iOS 6 I am able to get an access token, but am unable to access a resource, the server responds with a status code of 401 unauthorized. This is against a custom Rails 3 API backend using doorkeeper as the OAuth provider. The following client ruby code, using the OAuth2 gem, works OK:</p> <pre><code>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 </code></pre> <p>The iOS code is as below, in the login button handler I authenticate using the username and password, and store the credentials:</p> <pre><code>- (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:@""]; }]; } </code></pre> <p>and I've subclassed <code>AFHTTPClient</code> for my endpoint and in <code>initWithBaseURL</code> it retrieves the credentials and sets the authorization header with the access token:</p> <pre><code>- (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; } </code></pre> <p>Is this the correct way to use AFOAuth2Client and AFNetworking? And any idea why this is not working?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload