11436 SSO

OAuth 2.0 Support in Apigee Android and iOS SDKs

robertwalsh
Jan 20, 2015

OAuth 2.0 is an essential part of securing many APIs and in turn is important for many mobile applications. With the latest release of Apigee’s iOS and Android SDKs, we’ve added the ability to authenticate an API from generic OAuth 2.0 endpoints.  

There are four different grant types that can be used when authenticating a given API. Each of these grant types can easily be used in both of our mobile SDKs.

iOS SDK: Get an access token

To get an access token using the iOS SDKs ApigeeDataClient class, call one of the methods described below. Each method is asynchronous and works on background threads. When the method has completed, the ApigeeOAuth2CompletionHandler block containing the access token data is executed.


/*! OAuth2 grant_type 'password' */
-(void)accessTokenWithURL:(NSString*)accessTokenURL
                username:(NSString*)userName
                password:(NSString*)password
                clientID:(NSString*)clientID
       completionHandler:(ApigeeOAuth2CompletionHandler)completionHandler;

/*! OAuth2 grant_type 'client_credentials' */
-(void)accessTokenWithURL:(NSString*)accessTokenURL
                clientID:(NSString*)clientID
            clientSecret:(NSString*)clientSecret
       completionHandler:(ApigeeOAuth2CompletionHandler)completionHandler;

/*! OAuth2 grant_type 'code' or 'token' */
-(void)authorizeOAuth2:(NSString*)serviceProvider
         authorizeURL:(NSString*)authorizeURL
             tokenURL:(NSString*)tokenURL
          redirectURL:(NSString*)redirectURL
             clientID:(NSString*)clientID
         clientSecret:(NSString*)clientSecret
                scope:(NSString*)scope
     keyChainItemName:(NSString*)keyChainItemName
navigationController:(UINavigationController*)navigationController
    completionHandler:(ApigeeOAuth2CompletionHandler)completionHandler;

Once you’ve received the access token data, you can manage the storage and retrieval with easy-to-use methods that employ keychain built-in to the core iOS SDK framework for storage.


/*! Stores the given OAuth2 access token and refresh token into the keychain under the given name. */
-(void)storeOAuth2TokensInKeychain:(NSString*)keychainItemName
                      accessToken:(NSString*)accessToken
                     refreshToken:(NSString*)refreshToken
                            error:(NSError**)error;

/*! Retrieves the OAuth2 access token and refresh token from the keychain with the given name. */
-(void)retrieveStoredOAuth2TokensFromKeychain:(NSString*)keychainItemName
                           completionHandler:(ApigeeOAuth2CompletionHandler)completion;

/*! Removes the OAuth2 access token and refresh token from the keychain with the given name. */
-(void)removeStoredOAuth2TokensFromKeychain:(NSString*)keychainItemName;

Android SDK: Get an access token

The client_credentials and password grant types each have methods for both asynchronous and synchronous authentication. In the Android SDK ApigeeDataClient class, you can gather the access token data simply by calling these methods:


/*! OAuth2 grant_type 'client_credentials' asynchronous */
   public void oauth2AccessTokenAsync(final String accessTokenURL, final String clientId, final String clientSecret, OAuth2ResponseCallback callback)

/*! OAuth2 grant_type 'client_credentials' synchronous */
   public TokenResponse oauth2AccessToken(String accessTokenURL, String clientId, String clientSecret)

/*! OAuth2 grant_type 'password' asynchronous */
   public void oauth2AccessTokenAsync(final String accessTokenURL, final String username, final String password, final String clientId, OAuth2ResponseCallback callack)

/*! OAuth2 grant_type 'password' synchronous */
   public TokenResponse oauth2AccessToken(String accessTokenURL, String username, String password, String clientId)

The other two grant types, code and token, use a three-legged approach and require a webview in order to authenticate. The Android SDK has convenient methods to generate activities that display a webview within your application, authenticate the user, and retrieve the access token data.  


/*! OAuth2 grant_type 'code' intent */
   public Intent oauth2AccessTokenAuthorizationCodeIntent(Context context,String authorizationCodeURL, String accessTokenURL, String redirectURL, String clientId, String clientSecret)

/*! OAuth2 grant_type 'token' intent */
   public Intent oauth2AccessTokenImplicitIntent(Context context,String authorizationCodeURL, String accessTokenURL, String redirectURL, String clientId, String clientSecret)

Calling these methods returns an activity which can then be started. Once the authorization is complete, you can retrieve the access token data from the returned intent object’s extras. Accessing the access token data is demonstrated below.


@Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == Constants.kImplicitRequestCode) {
           if (resultCode == RESULT_OK) {
               String token = data.getStringExtra(OAuth2WebViewActivity.OAuth2AccessTokenExtraKey);
               if( token != null ) {
                   this.tokenResponse = new TokenResponse();
                   this.tokenResponse.setAccessToken(token);
                   this.tokenResponse.setRefreshToken(data.getStringExtra(OAuth2WebViewActivity.OAuth2RefreshTokenExtraKey));
                   this.tokenResponse.setExpiresInSeconds(data.getLongExtra(OAuth2WebViewActivity.OAuth2RefreshTokenExtraKey, 0l));
                   this.accessTokenTextView.setText(token);
               }
           }
       }
   }

Once you’ve received the access token you can manage the storage and retrieval with some simple methods. The Android SDK uses the built-in FileDataStoreFactory for storage.


/*! Stores the given OAuth2 access token and refresh token into the FileDataStore under the given name. */
   public Boolean storeOAuth2TokenData(String storageId, TokenResponse tokenResponse)

/*! Retrieves the OAuth2 access token and refresh token from the FileDataStore with the given name. */
   public TokenResponse getOAuth2TokenDataFromStore(String storageId)

/*! Removes the OAuth2 access token and refresh token from the FileDataStore with the given name. */
   public void deleteStoredOAuth2TokenData(String storageId)

Implementing OAuth 2.0 in your Android or iOS mobile applications can be frustrating and take a lot of time and code. Using Apigee’s SDKs helps ease those frustrations and saves app developers time and effort.  

To see the iOS code in action you can check out this video. You can also explore our OAuth 2.0 sample application, which is included within both the iOS and Android SDKs.

Microservices Done Right

Next Steps

 
 

Resources Gallery

News