How to secure your Python Flask Routes with Basic Auth in 5 Minutes

Maximilian Ott
TEK Society
Published in
2 min readAug 28, 2020

“It works on my machine” — well known statement of a developer. Don’t forget to secure your routes before deploying to the cloud.

Photo by chris panas on Unsplash

Deploying your Flask Server to any cloud helps to make them publicly accessible via the internet. But: This does also mean it is accessible to everyone. Therefore you should secure your Python Flask Routes with at least Basic Auth. I’ll explain you how this works, so that you can deploy your server quickly.

First set up your Flask Server with your different routes. I am using /hello as an example :

from flask import Flask
app = Flask(__name__)
@app.route('/hello')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
print('Starting app')
app.run(host='0.0.0.0', debug=True, port=8080)

If you would deploy this server, everybody on the internet would be able to call your route (in case you do not provide any other security measures). Therefore we need to secure the route — and the easiest and probably fastest way is to use a basic authentication for that. First, you need to import HTTPBasicAuth:

from flask_httpauth import HTTPBasicAuthauth = HTTPBasicAuth()

Second, you need to define your decorator with the verify password function:

@auth.verify_password
def verify_password(username, password):
if username in users:
return check_password_hash(users.get(username), password)
return False

Now you have basically all the functionality you need. You just need to retrieve the possible user/password combinations (I’ve hardcoded one example for demonstration purposes— please don’t do that!):

user = 'jane.doe@email.com'
pw = '1234xyz'
users = {
user: generate_password_hash(pw)
}

Lastly, we miss only one step which is applying the authentication to our route. You do this by adding the login_required decorator to the appropriate routes. In my case, I would just modify the prior defined /hello route like this:

@app.route('/hello')
@auth.login_required
def hello_world():
return 'Hello, World!'

Now the route is secured and nobody can send successful requests without providing the required login credentials. The same applies to you, therefore don’t forget to add Basic Auth, User and Password to your HTTP calls when calling the API — otherwise you’ll get a 401 Unauthorized as well ;-)

--

--

Maximilian Ott
TEK Society

Avid Pragmatist trying to solve Business Problems — do you want to help?