We will write a simple Python Flask application that requires authentication in order to respond with a 200 HTTP Status code.
Python Flask Application:
Our Python Flask application will require the Header x-api-key dhuejso2dj3d0
in the HTTP Request, to give us a 200 HTTP Status code, if not, we will respond with a 401 Unauthorized Response:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
To get the headers, you can use headers.get("X-Api-Key")
or headers["X-Api-Key"]
Create a virtual environment, install flask and run the app:
1 2 3 4 5 6 7 8 9 |
|
Requests to our App:
Let’s first make a request with no headers, which should then give us a 401 Unautorhized response:
1 2 3 4 5 6 7 8 9 |
|
Now let’s include the authentication token in our headers. If the string is the same as the one in the code, we should see a 200 HTTP Response:
1 2 3 4 5 6 7 8 9 |
|
Note:
From a best practice, its not a good decision to hard code sensitive details in your code, but rather read that from an encrypted database and store that in your applications environment variables, and let your application read from the environment variables, something like that :D