|
| 1 | +# Approov Token Binding Quickstart |
| 2 | + |
| 3 | +This quickstart is for developers familiar with the Python Django framework who are looking for a quick intro into how they can add [Approov](https://approov.io) into an existing project. Therefore this will guide you through the necessary steps for adding Approov with token binding to an existing Python Django API server. |
| 4 | + |
| 5 | +## TOC - Table of Contents |
| 6 | + |
| 7 | +* [Why?](#why) |
| 8 | +* [How it Works?](#how-it-works) |
| 9 | +* [Requirements](#requirements) |
| 10 | +* [Approov Setup](#approov-setup) |
| 11 | +* [Approov Token Check](#approov-token-binding-check) |
| 12 | +* [Try the Approov Integration Example](#try-the-approov-integration-example) |
| 13 | + |
| 14 | + |
| 15 | +## Why? |
| 16 | + |
| 17 | +To lock down your API server to your mobile app. Please read the brief summary in the [README](/README.md#why) at the root of this repo or visit our [website](https://approov.io/product.html) for more details. |
| 18 | + |
| 19 | +[TOC](#toc---table-of-contents) |
| 20 | + |
| 21 | + |
| 22 | +## How it works? |
| 23 | + |
| 24 | +For more background, see the overview in the [README](/README.md#how-it-works) at the root of this repo. |
| 25 | + |
| 26 | +The main functionality for the Approov token check is in the file [approov_middleware.py](/src/approov-protected-server/token-binding-check/hello/approov_middleware.py). Take a look at the `verifyApproovToken()` and `verifyApproovTokenBinding()` functions to see the simple code for the checks. |
| 27 | + |
| 28 | +[TOC](#toc---table-of-contents) |
| 29 | + |
| 30 | + |
| 31 | +## Requirements |
| 32 | + |
| 33 | +To complete this quickstart you will need both the Python and the Approov CLI tool installed. |
| 34 | + |
| 35 | +* Python - Follow the official installation instructions from [here](https://wiki.python.org/moin/BeginnersGuide/Download) |
| 36 | +* Approov CLI - Follow our [installation instructions](https://approov.io/docs/latest/approov-installation/#approov-tool) and read more about each command and its options in the [documentation reference](https://approov.io/docs/latest/approov-cli-tool-reference/) |
| 37 | + |
| 38 | +[TOC](#toc---table-of-contents) |
| 39 | + |
| 40 | + |
| 41 | +## Approov Setup |
| 42 | + |
| 43 | +To use Approov with the Python Django API server we need a small amount of configuration. First, Approov needs to know the API domain that will be protected. Second, the Python Django API server needs the Approov Base64 encoded secret that will be used to verify the tokens generated by the Approov cloud service. |
| 44 | + |
| 45 | +### Configure API Domain |
| 46 | + |
| 47 | +Approov needs to know the domain name of the API for which it will issue tokens. |
| 48 | + |
| 49 | +Add it with: |
| 50 | + |
| 51 | +```text |
| 52 | +approov api -add your.api.domain.com |
| 53 | +``` |
| 54 | + |
| 55 | +Adding the API domain also configures the [dynamic certificate pinning](https://approov.io/docs/latest/approov-usage-documentation/#approov-dynamic-pinning) setup, out of the box. |
| 56 | + |
| 57 | +> **NOTE:** By default the pin is extracted from the public key of the leaf certificate served by the domain, as visible to the box executing the Approov CLI command and the Approov servers. |
| 58 | +
|
| 59 | +### Approov Secret |
| 60 | + |
| 61 | +Approov tokens are signed with a symmetric secret. To verify tokens, we need to grab the secret using the [Approov secret command](https://approov.io/docs/latest/approov-cli-tool-reference/#secret-command) and plug it into the Python Django API server environment to check the signatures of the [Approov Tokens](https://www.approov.io/docs/latest/approov-usage-documentation/#approov-tokens) that it processes. |
| 62 | + |
| 63 | +Retrieve the Approov secret with: |
| 64 | + |
| 65 | +```text |
| 66 | +approov secret /path/to/approov/administration.tok -get base64 |
| 67 | +``` |
| 68 | + |
| 69 | +> **NOTE:** The `approov secret` command requires an administration management token to execute successfully. Developer management tokens don't have sufficient privileges to get the secret. |
| 70 | +
|
| 71 | +#### Set the Approov Secret |
| 72 | + |
| 73 | +Open the `.env` file and add the Approov secret to the var: |
| 74 | + |
| 75 | +```text |
| 76 | +APPROOV_BASE64_SECRET=approov_base64_secret_here |
| 77 | +``` |
| 78 | + |
| 79 | +[TOC](#toc---table-of-contents) |
| 80 | + |
| 81 | + |
| 82 | +## Approov Token Check |
| 83 | + |
| 84 | +To check the Approov token we will use the [jpadilla/pyjwt/](https://github.com/jpadilla/pyjwt/) package, but you are free to use another one of your preference. |
| 85 | + |
| 86 | +Add the [approov_middleware.py](/src/approov-protected-server/token-binding-check/hello/approov_middleware.py) class to your project: |
| 87 | + |
| 88 | +```python |
| 89 | +from django.http import JsonResponse |
| 90 | +from os import getenv |
| 91 | +from dotenv import load_dotenv, find_dotenv |
| 92 | +import base64 |
| 93 | +import jwt # https://github.com/jpadilla/pyjwt/ |
| 94 | +import hashlib |
| 95 | + |
| 96 | +# @link https://django.readthedocs.io/en/stable/topics/http/middleware.html |
| 97 | +class ApproovMiddleware: |
| 98 | + def __init__(self, get_response): |
| 99 | + self.get_response = get_response |
| 100 | + |
| 101 | + load_dotenv(find_dotenv(), override=True) |
| 102 | + |
| 103 | + # Token secret value obtained with the Approov CLI tool: |
| 104 | + # - approov secret <admin.tok> -get |
| 105 | + approov_base64_secret = getenv('APPROOV_BASE64_SECRET') |
| 106 | + |
| 107 | + if approov_base64_secret == None: |
| 108 | + raise ValueError("Missing the value for environment variable: APPROOV_BASE64_SECRET") |
| 109 | + |
| 110 | + self.APPROOV_SECRET = base64.b64decode(approov_base64_secret) |
| 111 | + |
| 112 | + def __call__(self, request): |
| 113 | + approov_token_claims = self.verifyApproovToken(request) |
| 114 | + |
| 115 | + if approov_token_claims == None: |
| 116 | + return JsonResponse({}, status = 401) |
| 117 | + |
| 118 | + if self.verifyApproovTokenBinding(request, approov_token_claims) == False: |
| 119 | + return JsonResponse({}, status = 401) |
| 120 | + |
| 121 | + return self.get_response(request) |
| 122 | + |
| 123 | + # @link https://approov.io/docs/latest/approov-usage-documentation/#backend-integration |
| 124 | + def verifyApproovToken(self, request): |
| 125 | + approov_token = request.headers.get("Approov-Token") |
| 126 | + |
| 127 | + # If we didn't find a token, then reject the request. |
| 128 | + if approov_token == None: |
| 129 | + # You may want to add some logging here. |
| 130 | + return None |
| 131 | + |
| 132 | + try: |
| 133 | + # Decode the Approov token explicitly with the HS256 algorithm to avoid |
| 134 | + # the algorithm None attack. |
| 135 | + approov_token_claims = jwt.decode(approov_token, self.APPROOV_SECRET, algorithms=['HS256']) |
| 136 | + return approov_token_claims |
| 137 | + except jwt.ExpiredSignatureError as e: |
| 138 | + # You may want to add some logging here. |
| 139 | + return None |
| 140 | + except jwt.InvalidTokenError as e: |
| 141 | + # You may want to add some logging here. |
| 142 | + return None |
| 143 | + |
| 144 | + # @link https://approov.io/docs/latest/approov-usage-documentation/#token-binding |
| 145 | + def verifyApproovTokenBinding(self, request, approov_token_claims): |
| 146 | + # Note that the `pay` claim will, under normal circumstances, be present, |
| 147 | + # but if the Approov failover system is enabled, then no claim will be |
| 148 | + # present, and in this case you want to return true, otherwise you will not |
| 149 | + # be able to benefit from the redundancy afforded by the failover system. |
| 150 | + if not 'pay' in approov_token_claims: |
| 151 | + # You may want to add some logging here. |
| 152 | + return True |
| 153 | + |
| 154 | + # We use the Authorization token, but feel free to use another header in |
| 155 | + # the request. Beqar in mind that it needs to be the same header used in the |
| 156 | + # mobile app to qbind the request with the Approov token. |
| 157 | + token_binding_header = request.headers.get("Authorization") |
| 158 | + |
| 159 | + if not token_binding_header: |
| 160 | + # You may want to add some logging here. |
| 161 | + return False |
| 162 | + |
| 163 | + # We need to hash and base64 encode the token binding header, because that's |
| 164 | + # how it was included in the Approov token on the mobile app. |
| 165 | + token_binding_header_hash = hashlib.sha256(token_binding_header.encode('utf-8')).digest() |
| 166 | + token_binding_header_encoded = base64.b64encode(token_binding_header_hash).decode('utf-8') |
| 167 | + |
| 168 | + if approov_token_claims['pay'] == token_binding_header_encoded: |
| 169 | + return True |
| 170 | + |
| 171 | + return False |
| 172 | +``` |
| 173 | + |
| 174 | +Now, to activate the [Approov Middleware](/src/approov-protected-server/token-binding-check/hello/approov_middleware.py) you just need to include it in the middleware list of your [Django settings](/src/approov-protected-server/token-binding-check/hello/settings.py) as the first one in the list: |
| 175 | + |
| 176 | +```python |
| 177 | +MIDDLEWARE = [ |
| 178 | + 'YOUR_APP_NAME.approov_middleware.ApproovMiddleware', |
| 179 | + 'django.middleware.security.SecurityMiddleware', |
| 180 | + # lines omitted |
| 181 | +] |
| 182 | +``` |
| 183 | + |
| 184 | +> **NOTE:** The Approov middleware is included as the first one in the list because you don't want to waste your server resources in processing requests that don't have a valid Approov token. This approach will help your server to handle more load under a Denial of Service(DoS) attack. |
| 185 | +
|
| 186 | +A full working example for a simple Hello World server can be found at [src/approov-protected-server/token-check](/src/approov-protected-server/token-binding-check). |
| 187 | + |
| 188 | +> **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 a `400`. |
| 189 | +
|
| 190 | +[TOC](#toc---table-of-contents) |
| 191 | + |
| 192 | + |
| 193 | +## Test your Approov Integration |
| 194 | + |
| 195 | +The following examples below use cURL, but you can also use the [Postman Collection](/README.md#testing-with-postman) 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. |
| 196 | + |
| 197 | +#### With Valid Approov Tokens |
| 198 | + |
| 199 | +Generate a valid token example from the Approov Cloud service: |
| 200 | + |
| 201 | +``` |
| 202 | +approov token -setDataHashInToken 'Bearer authorizationtoken' -genExample your.api.domain.com |
| 203 | +``` |
| 204 | + |
| 205 | +Then make the request with the generated token: |
| 206 | + |
| 207 | +```text |
| 208 | +curl -i --request GET 'https://your.api.domain.com/v1/shapes' \ |
| 209 | + --header 'Authorization: Bearer authorizationtoken' \ |
| 210 | + --header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE' |
| 211 | +``` |
| 212 | + |
| 213 | +The request should be accepted. For example: |
| 214 | + |
| 215 | +```text |
| 216 | +HTTP/1.1 200 OK |
| 217 | +
|
| 218 | +... |
| 219 | +
|
| 220 | +{"message": "Hello, World!"} |
| 221 | +``` |
| 222 | + |
| 223 | +#### With Invalid Approov Tokens |
| 224 | + |
| 225 | +##### No Authorization Token |
| 226 | + |
| 227 | +Let's just remove the Authorization header from the request: |
| 228 | + |
| 229 | +```text |
| 230 | +curl -i --request GET 'https://your.api.domain.com/v1/shapes' \ |
| 231 | + --header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE' |
| 232 | +``` |
| 233 | + |
| 234 | +The above request should fail with an Unauthorized error. For example: |
| 235 | + |
| 236 | +```text |
| 237 | +HTTP/1.1 401 Unauthorized |
| 238 | +
|
| 239 | +... |
| 240 | +
|
| 241 | +{} |
| 242 | +``` |
| 243 | + |
| 244 | +##### Same Approov Token with a Different Authorization Token |
| 245 | + |
| 246 | +Make the request with the same generated token, but with another random authorization token: |
| 247 | + |
| 248 | +``` |
| 249 | +curl -i --request GET 'https://your.api.domain.com/v1/shapes' \ |
| 250 | + --header 'Authorization: Bearer anotherauthorizationtoken' \ |
| 251 | + --header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE' |
| 252 | +``` |
| 253 | + |
| 254 | +The above request should also fail with an Unauthorized error. For example: |
| 255 | + |
| 256 | +```text |
| 257 | +HTTP/1.1 401 Unauthorized |
| 258 | +
|
| 259 | +... |
| 260 | +
|
| 261 | +{} |
| 262 | +``` |
0 commit comments