Basic authentication in Django

In this article we shall see how to work with basic authentication in django. But before that first let us see what Basic authentication is.

What is “Basic authentication“?

Basic authentication adds a header like below to the HTTP requests.

Authorization: Basic token

Basic authentication creates the token by taking a username and a password joins them with a colon(:) and Base64 encodes it.

So in order to get the username and password back we can get the token Base64 decode it and then split the string by colon (:).

Django view

The Django view to do this looks like this. I am using django-rest-framework for my API response.

The AuthTest class has a get method. So if we make a get request to the url having this class with the Basic auth token we can get the auth token and then continue with the rest of the process to retrieve the username and the password from the token.

We can match this username and password with the username and password that we have in our views file and if it matches we can return a success response with code 200, or if it did not match we can return 401 as unauthorised or if there is any exception we can return 400.