This quickstart is for developers familiar with Python who are looking for a quick intro into how they can add Approov into an existing project. Therefore this will guide you through the necessary steps for adding Approov to an existing Python Flask API server.
To lock down your API server to your mobile app. Please read the brief summary in the Approov Overview at the root of this repo or visit our website for more details.
For more background, see the Approov Overview at the root of this repo.
The main functionality for the Approov token check is in the file /servers/hello/src/approov-protected-server/token-check/hello_server_protected.py. Take a look at the _verifyApproovToken()
function to see the simple code for the check.
To complete this quickstart you will need both Python, Flask, and the Approov CLI tool installed.
- Python 3
- Flask
- Approov CLI - Learn how to use it here
To use Approov with the Python Flask API server we need a small amount of configuration. First, Approov needs to know the API domain that will be protected. Second, the Python Flask API server needs the Approov Base64 encoded secret that will be used to verify the tokens generated by the Approov cloud service.
Approov needs to know the domain name of the API for which it will issue tokens.
Add it with:
approov api -add your.api.domain.com
NOTE: By default a symmetric key (HS256) is used to sign the Approov token on a valid attestation of the mobile app for each API domain it's added with the Approov CLI, so that all APIs will share the same secret and the backend needs to take care to keep this secret secure.
A more secure alternative is to use asymmetric keys (RS256 or others) that allows for a different keyset to be used on each API domain and for the Approov token to be verified with a public key that can only verify, but not sign, Approov tokens.
To implement the asymmetric key you need to change from using the symmetric HS256 algorithm to an asymmetric algorithm, for example RS256, that requires you to first add a new key, and then specify it when adding each API domain. Please visit Managing Key Sets on the Approov documentation for more details.
Adding the API domain also configures the dynamic certificate pinning setup, out of the box.
NOTE: By default the pin is extracted from the public key of the leaf certificate served by the domain, as visible to the box issuing the Approov CLI command and the Approov servers.
Approov tokens are signed with a symmetric secret. To verify tokens, we need to grab the secret using the Approov secret command and plug it into the Python Flask API server environment to check the signatures of the Approov Tokens that it processes.
First, enable your Approov admin
role with:
eval `approov role admin`
For the Windows powershell:
set APPROOV_ROLE=admin:___YOUR_APPROOV_ACCOUNT_NAME_HERE___
Next, retrieve the Approov secret with:
approov secret -get base64
Open the .env
file and add the Approov secret to the var:
APPROOV_BASE64_SECRET=approov_base64_secret_here
To check the Approov token we will use the jpadilla/pyjwt/ package, but you are free to use another one of your preference.
First, add to your requirements.txt
file the JWT dependency:
PyJWT==1.7.1 # update the version to the latest one
Next, you need to install the dependency:
pip3 install -r requirements.txt
Now, add this code to your project, just before your first API endpoint:
from flask import Flask, jsonify, request, abort, g, make_response
# @link https://github.com/jpadilla/pyjwt/
import jwt
import base64
import hashlib
# @link https://github.com/theskumar/python-dotenv
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv(), override=True)
from os import getenv
api = Flask(__name__)
# Token secret value obtained with the Approov CLI tool:
# - approov secret -get
approov_base64_secret = getenv('APPROOV_BASE64_SECRET')
if approov_base64_secret == None:
raise ValueError("Missing the value for environment variable: APPROOV_BASE64_SECRET")
APPROOV_SECRET = base64.b64decode(approov_base64_secret)
@api.before_request
def _verifyApproovToken():
approov_token = request.headers.get("Approov-Token")
# If we didn't find a token, then reject the request.
if approov_token is None or approov_token == "":
# You may want to add some logging here.
return abort(make_response({}, 401))
try:
# Decode the Approov token explicitly with the HS256 algorithm to
# avoid the algorithm None attack.
g.approov_token_claims = jwt.decode(approov_token, APPROOV_SECRET, algorithms=['HS256'])
# When doesn't occur an exception we have a valid Aproov Token
except jwt.ExpiredSignatureError as e:
# You may want to add some logging here.
return abort(make_response({}, 401))
except jwt.InvalidTokenError as e:
# You may want to add some logging here.
return abort(make_response({}, 401))
except:
return abort(make_response({}, 401))
#@api.route("/")
#def hello():
# return jsonify({"message": "Hello World"})
NOTE: When the Approov token validation fails we return a
401
with an empty body, because we don't want to give clues to an attacker about the reason the request failed, and you can go even further by returning a400
.
Using the before_request
decorator approach will ensure that all endpoints in your API will be protected by Approov.
A full working example for a simple Hello World server can be found at /servers/hello/src/approov-protected-server/token-check.
The following examples below use cURL, but you can also use the Postman Collection to make the API requests. Just remember that you need to adjust the urls and tokens defined in the collection to match your deployment. Alternatively, the above README also contains instructions for using the preset dummy secret to test your Approov integration.
Generate a valid token example from the Approov Cloud service:
approov token -genExample your.api.domain.com
Then make the request with the generated token:
curl -i --request GET 'https://your.api.domain.com' \
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'
The request should be accepted. For example:
HTTP/1.1 200 OK
...
{"message": "Hello, World!"}
Generate an invalid token example from the Approov Cloud service:
approov token -type invalid -genExample your.api.domain.com
Then make the request with the generated token:
curl -i --request GET 'https://your.api.domain.com' \
--header 'Approov-Token: APPROOV_INVALID_TOKEN_EXAMPLE_HERE'
The above request should fail with an Unauthorized error. For example:
HTTP/1.1 401 Unauthorized
...
{}
If you find any issue while following our instructions then just report it here, with the steps to reproduce it, and we will sort it out and/or guide you to the correct path.
If you wish to explore the Approov solution in more depth, then why not try one of the following links as a jumping off point: