Start Here

This is an introductory guide to get you up and running quickly with Approov. For more detailed instructions see the relevant reference sections. Approov allows you to categorize mobile API traffic; you can distinguish between legitimate apps and fraudulent sources. It provides a way to authenticate the software being used to access your API. This allows you to put in place policies to monitor, shape or block traffic that does not come from an official app.

Requirements

In order to integrate Approov you will need:

  • An Approov account (sign up on the website, there is also a free demo with its own instructions that allows you to try a simple integration).
  • A development server exposing the API that you want to protect.
  • An Android or iOS app that communicates with that API.
  • A development environment to compile the app. More detailed software requirements are available on the Android and iOS reference pages.
  • Login details for the Approov Admin Portal.
  • The token secret for your account.

Setup

As part of the sign-up process you will have been given credentials to log in to the Admin Portal. You will need both the admin_access.tok and library_access.tok files. The admin access token allows you to use the Admin Portal. The library access token has an additional permission that allows you to download fresh libraries.

Once you have submitted your credentials you should navigate to the Libraries tab. This view shows a list of all of the libraries that have been created for this account (each new library is custom built). It also shows how many apps have been registered against a particular library and allows you to manage individual app registrations.

Begin by downloading the Integration Tools to your development machine. The archive includes registration scripts for Linux, Windows and Mac. Next click on the ‘New Library’ button. This will take you to a screen where you can select the platform you want to download the library for (Android or iOS). Choose the platform and click ‘Create Library’. A new library will be configured and made available. It should appear in the list of new libraries. Cick on the download icon to copy it to your machine. Select the ‘Libraries’ tab again to go back to the main list of libraries.

The other piece of information you will need to have is the token secret for your account. You received this as part of your initial signup. You can also copy it from the ‘Settings’ page of the admin portal. It is encoded in base64.

Note

Each Approov library has the same API, but has a unique implementation as a security feature. If you wish to update your library you can simply replace an existing one and your app should work exactly the same.

Server Integration

The first step in integrating Approov is to configure the server to check for the presence of a valid token. We recommend you add the token as a header in requests to the servers that you want to protect. The best way to integrate the token checking logic is dependent on your server architecture but the steps you have to take are common to any implementation:

  • Check for the presence of the header containing the Approov token.
  • Extract the token.
  • Verify the token is correctly signed with your secret.

Optional:

  • Extract information from the token claims.
  • Make a decision of what to do based on the information in the token.

The simplest logic is to only allow traffic with a signed Approov token and to reject everything else. Before deploying the solution, look at the Server Integration documentation for details of some things you might need to consider, but for this example we are just going to do the most basic check.

Here we have a simple server that we want to protect:

Examples

Python
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
   return "Hello World!\n"

if __name__ == "__main__":
   app.run()

All the server does is return “Hello World!”. To check that the client app that is being used to access the API is genuine, we need to extract a token from a header and verify it is signed with our secret:

Examples

Python
from flask import Flask, request, abort
import jwt
import json
import base64

app = Flask(__name__)

SECRET = bytes("VG9rZW4gU2VjcmV0","ascii")

# Function to check the validity of the token
def verifyToken(token):
  try:
    # Decode our token, allowing only the HS256 algorithm, using our base64
    # encoded SECRET
    tokenContents = jwt.decode(token, base64.b64decode(SECRET), algorithms=['HS256'])
    return tokenContents
  except jwt.ExpiredSignatureError as e:
    # Signature has expired, token is bad
    return None
  except jwt.InvalidTokenError as e:
    # Token could not be decoded, token is bad
    return None


@app.route("/")
def hello():
  # Get the Approov Token from header
  token = request.headers.get("approov-token")
  # If we  didn't find a token, then reject the request
  if token == "":
    abort(401)
  tokenContents = verifyToken(token)
  if (tokenContents == None):
    abort(401)
  return "Hello World!\n"

if __name__ == "__main__":
   app.run()

We could also implement more complex checks or behaviours, but for now we will just block all traffic. The API will now only respond to requests which contain an “Approov-Token” header which contains a valid JWT from our SDK.

Client Integration

The next step is to set up a client. We need to add the library to the build process, initialize it, then use it.

The Approov SDK is made available as a library module (.aar) on Android or a framework on iOS and should be imported into your project in the normal way. The Android documentation has instructions for adding a library as a dependency and the iOS documentation has instructions for embedding frameworks.

Initialization

Once the SDK is available in your development environment, on Android you will need to initialize the library instance. In iOS the library is initialized automatically as a singleton, on Android we have to create the Attestation object manually.

Examples

Android
public class MyApp extends Application {

    public void onCreate () {
        ...
      // Initialize the Approov SDK
      try {
        ApproovConfig aConfig = ApproovConfig.getDefaultConfig(getApplicationContext());
        ApproovAttestation.initialize(aConfig);
      } catch (IllegalArgumentException ex) {
        Log.e(TAG, ex.getMessage());
      } catch (MalformedURLException ex) {
        Log.e(TAG, ex.getMessage());
      }
        ...
    }
}

Getting a Token

Once you have the SDK integrated and initialized, you can use it to get a token that verifies the authenticity of the app used to access the API. Do that just before every API call that needs to be protected. The SDK caches the token for you and gets a new one if required.

Examples

Android
// Always populate the token string
String aToken = "NOTOKEN";
// Fetch a token specifying the domain we are about to access.
TokenInterface.ApproovResults aFetchResults
    = ApproovAttestation.shared()
    .fetchApproovTokenAndWait("www.myapi.io");
if (aFetchResults.getResult() == AttestationResult.SUCCESS) {
   aToken = aFetchResults.getToken();
} else {
  // handle the failure
}
// Create a header with the aToken string in your HTTPS request and
// send to the server (www.myapi.io) as normal.
iOS - Swift
// Always populate the token string
var approovToken = "NOTOKEN"
// Fetch a token specifying the domain we are about to access.
if let tokenResult = ApproovAttestee.shared()?.fetchApproovTokenAndWait("www.myapi.io") {
  switch tokenResult.result {
    case .successful:
      approovToken = tokenResult.approovToken
    }
    case .failed:
      // handle the failure
    }
  }
}
// Create a header with the aToken string in your HTTPS request and
// send to the server (www.myapi.io) as normal.
iOS - Objective-C
// Always populate the token string
NSString *approovToken = @"NOTOKEN";
// Fetch a token specifying the domain we are about to access.
ApproovTokenFetchData *tokenResult = [[ApproovAttestee sharedAttestee] fetchApproovTokenAndWait:@"www.myapi.io"];
switch (tokenResult.result) {
  case ApproovTokenFetchResultSuccessful:
  {
      *approovToken = tokenResult.approovToken;
      break;
  }
  case ApproovTokenFetchResultFailed:
  {
      // handle the failure
      break;
  }
}
// Create a header with the aToken string in your HTTPS request and
// send to the server (www.myapi.io) as normal.

There are also asynchronous versions of these calls that may be more suitable for your app flow.

Note

Once you have a token it must be protected. Tokens should only be transmitted across HTTPS connections protected with Certificate Pinning. If Certificate Pinning is not available then use Dynamic Pinning with MITM Detection to protect the token instead.

For more information on the client integration process, see the Android Client or iOS Framework documentation.

App Registration

Integrating the library gets us almost there, but we need to register our app so that the Approov servers can identify it. To do that we use the integration tools downloaded from the admin portal. To prove you are authorized to upload a new app signature you need to provide the registration credentials that were part of your download. You also need to pass the app you want to register to the tool.

Examples

Command Line
./registration -a MyApp.apk -t registration_access.tok -e 1w -V beta

The above command registers MyApp.apk with Approov (MyApp.ipa for iOS) for 1 week with a version name of “beta”. Specifying the expiry (-e) is optional but useful for temporary test builds.

For more information on registration, see the Application Registration documentation.

Testing the App

Once you have integrated with the server and client and registered the app successfully, you can run it and verify that it can use the protected API. Only tokens which have been signed with the token secret will be validated by the server logic. Any other requests will be automatically rejected.

Note

Developing and testing your app: The Approov service fails attestations when the authenticating app is unregistered or when the Approov SDK detects that a debugger is attached. This means that your app will typically receive invalid tokens while you are developing and whenever you are debugging it. We recommend you develop and test your app against a debug version of your server with token checking enbled or disabled based on the type of testing you are doing. Alternatively, you can use the device ID embedded in a token to add a whitelist capability to your server code which would always grant access to whitelist devices. If you use this latter option, then please ensure the collection of whitelisted devices is kept to a minimum and that the facility is kept disabled as much as possible.