Flask: Basic authentication

In this Flask tutorial, we will check how to get the username and the password from a HTTP request made to a Flask server with basic authentication.

 

Introduction

In this Flask tutorial, we will check how to get the username and the password from a HTTP request made to a Flask server with basic authentication. If you haven’t yet used Flask, please consult this getting started tutorial.

In this simple authentication mechanism, the client sends the HTTP request with an Authorization header, which contains both the password and the username [1].

This Authorization header has the following format, with the content underlined encoded as a base64 string [1]:

Authorization: Basic username:password

Important: In this tutorial we will simply cover the basic authentication part of the request, more precisely, how to get the password and username from the client request sent in the authorization header.

This authentication scheme doesn’t guarantee data privacy and the base64 applied by the client is a reversible encoding, so we should consider that the data is sent from the client to the server in plain text [2].

Thus, it’s trivial for an attacker to steal the credentials sent in the authorization header if we are using HTTP. In order to securely send the credentials, we should use the basic authentication mechanism with HTTPS to ensure data is encrypted before transmission, specially when dealing with sensitive information.


The code

We will start our code by importing the Flask class from the flask module, so we can create and configure our application.

We will also need to import the request global object, which allows us to access the parsed incoming request data [3]. Note that although this is a global object, Flask will guarantee that we get the correct data in each request even in multi-threaded environments [3].

from flask import Flask
from flask import request

Next we will create a Flask class instance, which will be our app. As input of the constructor, we pass the name of our application.

app = Flask("my app")

Next we will define the route where our server will be listening for incoming requests and the handling function that will be executed when the request is received on that route. Note that we are not specifying the HTTP methods allowed and thus, by default, this route will only answer to HTTP GET requests [4].

@app.route('/auth') 
def authRouteHandler(): 
    ## handling function code

Inside the handling function, the basic authentication information is stored on the authorization object of the request global object we have imported in the beginning of the code.

The authorization object is of class werkzeug.datastructures.Authorization, but we can access it in Python’s dictionary style.

So, we can access both the username and the password sent by the client by using those strings as keys of the dictionary.

print(request.authorization["username"]) 
print(request.authorization["password"])

To finalize the handling function we will return an “ok” message to the client.

return "ok"

Finally, we will run our app by calling the run method on the app object. We will configure it to listen on all the IPs available (by specifying the host as “0.0.0.0“) and on port 8090. The full source code can be seen below.

from flask import Flask
from flask import request

app = Flask("my app")

@app.route('/auth')
def authRouteHandler():

    print(request.authorization["username"])
    print(request.authorization["password"])

    return "ok"

app.run(host = '0.0.0.0', port = 8090)


Testing the code

To test the code, we will use the loopback IP address 127.0.0.1. As a tool to make the HTTP request with the authorization, we will use Postman.

So, after running the Python code we have developed, open Postman. On the dropdown left to the HTTP request destination URL, select GET. As mentioned before, since we didn’t specify the HTTP methods allowed, the “/auth” route we created on the server will only answer to GET requests.

On the request destination URL, write the line below. As mentioned, we will use the loopback IP address and port 8090, which was the one we specified in the code.

http://127.0.0.1:8090/auth

Then, click on the Authorization tab below the HTTP methods dropdown. On the view that opens, go to the Type dropdown and select “Basic Auth“.

Then, fill the username and password fields with some testing values. For this tutorial, I’ve used “testUser” and “testPass”.

Finally, click the send button so the request is sent to the Flask server. You should receive an “ok” message upon execution of the request. You can check all the mentioned configurations below at figure 1.

Flask basic HTTP authorization.png

Figure 1 – Postman configured for basic authentication.

If you go back to the Python shell, you should get an output similar to figure 2, which shows the credentials sent in the HTTP request being printed. Naturally, in a real application scenario, we would then use these credentials to confirm if the user was authorized to perform the request or not.

Flask basic HTTP authorization received from Postman.png

Figure 2 – Output in Python’s prompt. Tested on the Python IDLE IDE.


References

[1] https://swagger.io/docs/specification/authentication/basic-authentication/

[2] https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication

[3] http://flask.pocoo.org/docs/0.12/api/#flask.request

[4] http://flask.pocoo.org/docs/0.12/quickstart/

Advertisements

2 Replies to “Flask: Basic authentication”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s