Follow

Integrate Shape Mobile SDK with iOS App

 

Description

  • Instructions for integrating Shape Mobile SDK with iOS applications.

Return to Configuring Mobile Client (Mobile SDK Integration) 

Return to Integrating Shape Defense

 

Environment

  • Shape Defense for Mobile
  • iOS

 

Procedure

Download from the Shape Security section of the Silverline Portal:

  • The Mobile SDK library

  • A base configuration file for Android

mceclip0.png

 

Step 1: Setup

Choose either Static or Dynamic XCFramework based on your requirements:

Static Framework

1.1 Import the Framework

  1. Extract APIGuard_iOS_v<version number>.zip available inside SDK_iOS_v4.1.x_GA_binaryfiles.zip to access the static framework.
  2. Drag the APIGuard.xcframework to your Xcode project.
  3. Make sure the Copy items if needed checkbox is checked in the Choose options for adding these files dialog.

1.2 Build Configuration

  1. In the Frameworks, Libraries, and Embedded Content section located in the General tab of the project settings in Xcode, select Do Not Embed.
  2. In Build Settings, select your application's target:
  • Set Deployment Postprocessing (DEPLOYMENT_POSTPROCESSING) flag to YES.
  • Set Strip Linked Product (STRIP_INSTALLED_PRODUCT) flag to YES.
  • Set Strip Style (STRIP_STYLE) to All Symbols.

Note: Deployment post-processing is the driving flag for strip-related flags. If it is set to YES then strip-related flags come into effect.

Shape requires these settings for Release/Appstore configuration of your application so that unnecessary symbols are stripped off after linking Mobile SDK to your application. Failure to enable these flags in Release/Appstore configuration could leak some SDK and application symbols.

 

Dynamic Framework

1.1 Import the Framework

  1. Extract APIGuard_iOS_Dynamic-v<version number>.zip available inside SDK_iOS_v4.1.x_GA_binaryfiles.zip to access the dynamic framework.
  2. Drag the APIGuard.xcframework to your Xcode project.
  3. Make sure the Copy items if needed checkbox is checked in the Choose options for adding these files dialog.

1.2 Build Configuration

  1. In the Frameworks, Libraries, and Embedded Content section located in the General tab of the project settings in Xcode, select Embed & Sign.

 

1.3 Add base configuration:

Drag the base configuration JSON file for iOS into Xcode as project level.

 

Step 2: Initialize Mobile SDK

2.1 Import APIGuard

Add an import statement to every file that uses the Mobile SDK API.

import APIGuard

 

2.2 Initialize SDK

In your app’s AppDelegate class,

  • Conform to APIGuardDelegate protocol.

inside didFinishLaunchingWithOptions(),

  • Add the Bundle Resource Path for the base config file.
  • Call initialize().

For more information for input parameters, see API Reference.

Initialization example (Swift):

@UIApplicationMain

class AppDelegate: APIGuardDelegate {

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {

 

    // this example looks for the file baseConfig.json in the project.

    if let bundleResourcePath = Bundle.main.path(forResource: "baseConfig", ofType: "json"),

        let apiGuard = APIGuard.sharedInstance() {

 

            // this example uses "default" environment for updating the configuration

            apiGuard.initialize(withConfigFile: bundleResourcePath, withEnvironment: "default", delegate: self)

        }

 

    return true

}

Initialization example (Objective-c):

@implementation AppDelegate : UIResponder <UIApplicationDelegate,APIGuardDelegate>

 

- (BOOL)application:(UIApplication *)application

              didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

        // Override point for customization after application launch.

        // Initialize APIGuard

 

        NSString *bundleResourcePath = [[NSBundle mainBundle] pathForResource:@"baseConfig"

                                   ofType:@"json"];

 

        // this example uses "default" environment for updating the configuration

        [[APIGuard sharedInstance] initializeWithConfigFile:bundleResourcePath withEnvironment:@"default"

            delegate:self];

 

        return YES;

    }

2.3 Implement Delegate Methods

You must implement the following two delegate methods in AppDelegate after conforming to APIGuardDelegate protocol:

checkCertificates(_ challenge: URLAuthenticationChallenge)

Mobile SDK calls this method to let the app check the validity of the certificates when connection is being established to update the Shape configuration. Shape recommends implementing this function as it provides app developers with certificate pinning functionality.

log(_ string: String)

Mobile SDK calls this method when it needs to log a message for debugging purposes. These messages are intended for developers; do not log them to the system log in production apps. The Troubleshooting Guide includes common error codes which are logged by Mobile SDK.

The following two delegate methods are optional.

initializationSuccess()

This callback gets called on SDK initialization success. SDK will call this method on a background thread.

initializationFailure(_ error: String)

This callback gets called if SDK initialization fails. The failure reason is passed as a string. This function is called on a background thread.

Callback example (Swift):

func log(_ string: String) {

    print(string)

}

 

func checkCertificates(_ challenge: URLAuthenticationChallenge) -> Bool {

    /* Allows to implement certificate pinning on configuration update requests. Return true if the certificate is valid, false to prevent the connection. 

Return true when no certificate pinning is required.

*/

 

    return true

}

 

func initializationSuccess() {

    // Gets called if initialization for APIGuard is successful. Note that callbacks are for informational purposes only; they are not designed to handle logic.

 

}

 

func initializationFailure(_ error: String) {

    // Gets called if initialization for APIGuard fails. The failure reason is passed as a string.

}

Callback example (Objective-c):

func log(_ string: String) {

    print(string)

}

func checkCertificates(_ challenge: URLAuthenticationChallenge) -> Bool {

    /* Allows to implement certificate pinning on configuration update requests. Return true if the certificate is valid, false to prevent the connection. 

Return true when no certificate pinning is required.

*/

 

    return true

}

func initializationSuccess() {

    // Gets called if initialization for APIGuard is successful. Note that callbacks are for informational purposes only; they are not designed to handle logic.

}

func initializationFailure(_ error: String) {

    // Gets called if initialization for APIGuard fails. The failure reason is passed as a string.

}

 

Step 3: Request Decoration and Response Parsing

Decorating is the process of appending the Shape headers to the request. Before an API call is sent, the SDK must decorate each request object for protected endpoints.

  1. To add the HTTP headers to request objects you use, call getRequestHeaders.
  2. Pull the headers from the response object you use and pass them to parseResponseHeaders.

You can also use the initializationSuccess() callback or a state property to confirm that the APIGuard object is ready for decoration.

Request decoration/parse response example (Swift):

// Generate Shape headers and add headers to request

if let apiGuard = APIGuard.sharedInstance(), let url = request.url,

let apiGuardHeaders = apiGuard.getRequestHeaders(url.absoluteString, body: request.httpBody) {

for (key, value) in apiGuardHeaders {

    request.addValue(value, forHTTPHeaderField: key)

  }

}

 

// Sample response (in request completion callback)

if let apiGuard = APIGuard.sharedInstance(), let response = response {

  if let httpResponse = response as? HTTPURLResponse, let headers = httpResponse.allHeaderFields as? [String : String] {

    apiGuard.parseResponseHeaders(headers)

  }

}

Request decoration/parse response example (Objective-c):

// Generate Shape headers

NSDictionary <NSString *, NSString *> *apiGuardHeaders = [APIGuard.sharedInstance

    getRequestHeaders:request.URL.absoluteString body:request.HTTPBody];

 

// Add headers to request

[apiGuardHeaders enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString  *

    _Nonnull value, BOOL * _Nonnull stop) {

  [request setValue:value forHTTPHeaderField:key];

}];

 

// Sample Response (if not of type NSURLResponse)

// Inside request completion callback

NSDictionary<NSString *, NSString *> *responseHeaders = [(NSHTTPURLResponse *)response allHeaderFields];

[[APIGuard sharedInstance] parseResponseHeaders:responseHeaders];

 

Step 4: Running your code

Once compiled and running, you should observe output from the log() callback. A successful SDK initialization will result in M0 being reported. M1 and M2 signify a successful configuration fetch. Any state which begins with “E” or “F” (e.g. E10), signifies an error. Not all errors are critical.

Please refer to the Troubleshooting Guide for iOS SDK for explanations of some common error codes.

A properly integrated Shape SDK will result in protected requests being decorated with Shape headers. Shape headers will have the prefix of "guBJbWEZnL-". There may be one, seven, or eight headers with this prefix.

To validate that the SDK has been integrated properly, follow steps in Validate Shape Mobile SDK Integration [LINK]

 

 

Related Content

Return to Configuring Mobile Client (Mobile SDK Integration) 

Return to Integrating Shape Defense

 

 

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request