IBM Cloud Docs
Mobile apps

Mobile apps

With IBM Cloud® App ID, you can quickly construct an authentication layer for your native or hybrid mobile app.

Understanding the flow

A mobile flow is useful when you are developing an app that is to be installed on a user's device (a native application). By using this flow, you can securely authenticate users on your app to provide personalized user experiences across devices.

What is the flow's technical basis?

Since native applications are installed directly on a user's device, private user information and application credentials can be extracted by third-parties with relative ease. By default, these types of applications are known as untrusted clients as they cannot store global credentials or user refresh tokens. As a result, untrusted clients require users to input their credentials every time their access tokens expire.

To convert your application into a trusted client, App ID uses Dynamic Client Registration. Before an application instance begins authenticating users, it first registers as an OAuth2 client with App ID. Because of client registration, your application receives an installation-specific client ID that can be digitally signed and used to authorize requests with App ID. Since App ID stores your application's corresponding public key, it can validate your request signature that allows your application to be viewed as a confidential client. This process minimizes your application's risk of exposing credentials indefinitely and greatly improves the user experience by allowing automatic token refresh.

Following registration, your users authenticate by using either the OAuth2 authorization code or resource owner password authorization grant flows to authenticate users.

Dynamic client registration

  1. A user triggers a request by the client application to the App ID SDK.
  2. If your app is not registered as a mobile client yet, the SDK initiates a dynamic registration flow.
  3. On a successful registration, App ID returns your installation-specific client ID.

Authorization flow

App ID mobile request flow
Figure 1. App ID mobile request flow

  1. The App ID SDK starts the authorization process by using the App ID /authorization endpoint.
  2. The login widget is displayed to the user.
  3. The user authenticates by using one of the configured identity providers.
  4. App ID returns an authorization grant.
  5. The authorization grant is exchanged for access, identity, and refresh tokens from the App ID /token endpoint.

Configuring your mobile app with the App ID SDKs

Get started with the App ID SDKs.

Before you begin

You need the following information:

  • An App ID instance

  • Your instance's tenant ID. This can be found in the Service Credentials tab of your service dashboard.

  • Your instance's deployment IBM Cloud region. You can find your region by looking at the console.

    Table 1. IBM Cloud regions and corresponding SDK values
    IBM Cloud Region SDK value
    US South AppID.REGION_US_SOUTH
    Sydney AppID.REGION_SYDNEY
    United Kingdom AppID.REGION_UK
    Germany AppID.REGION_GERMANY

Authenticating with the Android SDK

Protect your mobile applications by using the App ID client SDK.

Before you begin

You must have the following prerequisites before you can get started:

  • API 27 or higher
  • Java 8.x
  • Android SDK Tools 26.1.1+
  • Android SDK Platform Tools 27.0.1+
  • Android Build Tools version 27.0.0+

Installing the SDK

  1. Create an Android Studio project or open an existing project.

  2. Add the JitPack repository to your root build.gradle file.

       allprojects {
          repositories {
             ...
             maven { url 'https://jitpack.io' }
          }
       }
    
  3. Find your application's build.gradle file. Note: Be sure to open the file for your app, not the project build.gradle file.

    1. Add the App ID client SDK to the dependencies section.

      dependencies {
         compile group: 'com.github.ibm-cloud-security:appid-clientsdk-android:4.+'
      }
      
    2. In the defaultConfig section, configure the redirect scheme.

      defaultConfig {
      ...
      manifestPlaceholders = ['appIdRedirectScheme': android.defaultConfig.applicationId]
      }
      
  4. Synchronize your project with Gradle. Click Tools > Android > Sync Project with Gradle Files.


Initializing the SDK

  1. Pass the context, tenant ID, and region parameters to the initialize method to configure the SDK.

    A common, though not mandatory, place to put the initialization code is in the onCreate method of the main activity in your Android application.

    AppID.getInstance().initialize(getApplicationContext(), <tenantID>, <region>);
    

Authenticating with the iOS Swift SDK

Protect your mobile applications by using the App ID client SDK.

Before you begin

You must have the following prerequisites before you get started:

  • Xcode 9.0 or higher
  • CocoaPods 1.1.0 or higher
  • iOS 10.0 or higher

Installing the SDK

The App ID client SDK is distributed with CocoaPods, a dependency manager for Swift and Objective-C Cocoa projects. CocoaPods downloads artifacts, and makes them available to your project.

  1. Create an Xcode project or open an existing one.

  2. Create a new or open your existing Podfile in the project's directory.

  3. Add the IBMCloudAppID pod and use_frameworks! command to your target's dependencies

    target '<yourTarget>' do
       use_frameworks!
       pod 'IBMCloudAppID'
    end
    
  4. Install your dependencies from the command line within your project directory.

    pod install --repo-update
    
  5. After installation, open the {your app}.xcworkspace file that contains your Xcode project and your linked dependencies

  6. Enable keychain sharing in your Xcode project. Navigate to Project Settings > Capabilities > Keychain Sharing and select Enable keychain sharing.

  7. Open Project Settings > Info > URL Types, and add a URL Type. Place the following value in both the Identifier and the URL Scheme text boxes.

    (PRODUCT_BUNDLE_IDENTIFIER)
    

Initializing the SDK

  1. Initialize the client SDK by passing the tenant ID and region parameters to the initialize method.

       AppID.sharedInstance.initialize(tenantId: <tenantID>, region: <region>)
    

    A common, though not mandatory, place to put the initialization code is in the application:didFinishLaunchingWithOptions method of the AppDelegate file of your Swift application.

  2. Import the App ID SDK to your AppDelegate file.

    import IBMCloudAppID
    
  3. Configure your application to process redirects through App ID.

    func application(_ application: UIApplication, open url: URL, options :[UIApplication.OpenURLOptionsKey : Any]) -> Bool {
          return AppID.sharedInstance.application(application, open: url, options: options)
       }
    

Accessing protected APIs

After a successful login flow, you can use your access and identity tokens to invoke protected backend resources that use the SDK or a networking library of your choice.

With the Swift SDK

  1. Add the following imports to the file in which you want to invoke a protected resource request:

    import BMSCore
    import IBMCloudAppID
    
  2. Invoke your protected resource

    BMSClient.sharedInstance.initialize(region: <region>)
    BMSClient.sharedInstance.authorizationManager = AppIDAuthorizationManager(appid: AppID.sharedInstance)
    let request =  Request(url: "{your protected resource url}")
    request.send { (response: Response?, error: Error?) in
       guard let response = response, error == null else {
             print("An error occurred invoking a protected resources", error?.localizedDescription ?? "No response was received")
             return;
       }
       // use your response object
    })
    

With the Android SDK

  1. Add the following imports to the file in which you want to invoke a protected resource request:

    import com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient;
    import com.ibm.cloud.appid.android.api.AppIDAuthorizationManager;
    
  2. Invoke your protected resource

    BMSClient bmsClient = BMSClient.getInstance();
    bmsClient.initialize(getApplicationContext(), <region>);
    AppIDAuthorizationManager appIdAuthMgr = new AppIDAuthorizationManager(AppID.getInstance())
    bmsClient.setAuthorizationManager(appIdAuthMgr);
    Request request = new Request("{your protected resource url}", Request.GET);
    request.send(this, new ResponseListener() {
    @Override
    public void onSuccess (Response response) {
          Log.d("My app", "onSuccess :: " + response.getResponseText());
    }
    @Override
    public void onFailure (Response response, Throwable t, JSONObject extendedInfo) {
          if (null != t) {
             Log.d("My app", "onFailure :: " + t.getMessage());
          } else if (null != extendedInfo) {
             Log.d("My app", "onFailure :: " + extendedInfo.toString());
          } else {
             Log.d("My app", "onFailure :: " + response.getResponseText());
             }
          }
    });
    

Without an SDK

With the library of your choice, set your Authorization request header to use the Bearer authentication scheme to transmit the access token.

Example request format:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer <accessToken> <optionalIdentityToken>

Next steps

With App ID installed in your application, you're almost ready to start authenticating users! Try doing one of the following activities next: