Skip to content

OAuth Support on RestKit

n8chur edited this page Feb 2, 2012 · 9 revisions

##Overview

RestKit includes support to consume resources from APIs which use OAuth as an access protocol for third-party applications. For OAuth1 the framework includes the TDOAuth library which implements the signature of each request.

##OAuth 1 To start the following information is required:

Application Identification

  • Consumer Key
  • Consumer Secret

You get this information once your application is registered in the API.

User Identification

  • Access Token
  • Access Token Secret

That information is provided by the user in order to give access to your application.

With this information you setup the RKClient to consume the resources from the API:

RKObjectManager* objectManager = [RKObjectManager sharedManager];
objectManager.client.baseURL = @"YOUR_BASE_URL";
objectManager.client.OAuth1ConsumerKey = @"YOUR CONSUMER KEY";
objectManager.client.OAuth1ConsumerSecret = @"YOUR CONSUMER SECRET";
objectManager.client.OAuth1AccessToken = @"YOUR ACCESS TOKEN";
objectManager.client.OAuth1AccessTokenSecret = @"YOUR ACCESS TOKEN SECRET";
objectManager.client.authenticationType = RKRequestAuthenticationTypeOAuth1;

##OAuth 2 OAuth 2 is the newer version of this protocol, but there is still under construction. RestKit support is based on the 22 draft version of it.

###Getting an access_token To get an access_token you can use the RKOAuthClient which will require the following information:

Application Identification

  • Client Id
  • Client Secret

You get this information once your application is registered in the API.

User Identification

  • Authorization Code

This authorization code is provided by the user.

With that information you can setup the client as following:

oauthClient = [RKClientOAuth clientWithClientID:[Client Id] secret:[Client Secret] delegate:[Your Delegate]];
[oauthClient setAuthorizationCode:[User Authorization Code]];
[oauthClient setAuthorizationURL:[Authorization Endpoint]];
[oauthClient setCallbackURL:[Your application callbackurl]];
[oauthClient validateAuthorizationCode];

Notice that your delegate will need to implement the methods according to RKOAuthClientDelegate.

###Consuming resources using an access_token Just give to your instance of RKClient the access_token you got as following:

RKObjectManager* objectManager = [RKObjectManager sharedManager];
objectManager.client.baseURL = @"YOUR API URL";
objectManager.client.OAuth2AccessToken = @"YOUR ACCESS TOKEN";
objectManager.client.authenticationType = RKRequestAuthenticationTypeOAuth2;

Final Recommendations

We strongly encourage you to keep access_token, refresh_token, clientId and clientSecret using the iOS Keychain or other secure storage ways.