Basic Authentication
HTTP Basic authentication implementation is the simplest technique for enforcing access controls to web pages because it doesn't require cookies, session identifier and login pages. Rather, HTTP Basic authentication uses static, standard fields in the HTTP header which means that no handshakes have to be done in anticipation. They are merely encoded with Base64 in transit, but not encrypted or hashed in any way. Basic Authentication is, therefore, typically used over HTTPS.
Django
Django is a powerful web framework, created in Python, which follows the DRY (Don't repeat yourself) ideology. Django apps are reusable by design and Extremely easy to unit-test.
Since you landed this tutorial, I am assuming you already know how to create a basic project in Django. This basic app deals with creating an app in django, url routing, creating models, enabling administration panel, templating. So basic knowledge in creating django apps is required.
This django application helps to create pages using django administration panel. basic auth is enabled only for pages which are marked as private. so when processing a page request, the app processes the request and pops up for authentication if the requested page is selected a protected.
Lets create the django app,
Install Django
pip install Django
It is recommended to use Virtual Environment.
Start django project
django-admin startproject basic_auth_django
Create pages app
python manage.py startapp pages
If you need any modifications in model make changes and migrate new model definition. Or just clone/copy the code for this demo django application from github.
Django project structure:
- basic_auth_django/
- basic_auth_django/
- __init__.py
- settings.py
- urls.py
- wsgi.py
- pages/
- migrations/
- __init__.py
- admin.py
- models.py
- tests.py
- urls.py
- views.py
- templates/
- pages/
- 404.html
- index.html
- page.html
- pages/
- db.sqlite3
- manage.py
- requirements.txt
- basic_auth_django/
Create & Migrate models
python manage.py makemigrations pages
python manage.py migrate
Basic authentication code snippet
# views.py
import base64
from django.contrib.auth import authenticate
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render_to_response
from .models import Page
def page_index(request):
pages = Page.objects.all()
return render_to_response('pages/index.html', {"pages": pages})
def page_view(request, slug, **kwargs):
try:
page = Page.objects.get(page_slug=slug)
except ObjectDoesNotExist:
return render_to_response('pages/404.html')
# If private page do basic auth
if page.is_private:
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
if auth[0].lower() == "basic":
uname, passwd = base64.b64decode(auth[1]).split(':')
user = authenticate(username=uname, password=passwd)
if user is not None and user.is_active:
request.user = user
return render_to_response('pages/page.html', {"page": page})
response = HttpResponse()
response.status_code = 401
response['WWW-Authenticate'] = 'Basic realm="%s"' % "Basci Auth Protected"
return response
else:
return render_to_response('pages/page.html', {"page": page})
Create admin
Create new admin user to access django admin panel.
python manage.py createsuperuser
Demo
python manage.py runserver
Admin panel
Login into the django admin panel via http://127.0.0.1:8000/admin and create pages.
Add pages
visit http://127.0.0.1:8000/pages/ to see list of pages created via django admin. visit one of the private pages and it will prompt for authentication.
Basic auth demo
Download
##Flask
Flask is a lightweight, micro web development framework for Python. Compared to the higher-level frameworks, it’s much more flexible with its powerful API.
This below flask app is very simple flat application which has two pages index and /private. private page is protected by basic auth. User name and password can be configured in check_auth method.
Install Flask
You may follow official flask documentation. It is recommended to use Virtual Environment. Follow Flask docs or simply install flask with pip install Flask
##Code example in Flask Flask project structure:
- basic_auth_flask/
- app.py
- requirements.txt
# app.py
from functools import wraps
from flask import Flask, request, Response
app = Flask(__name__)
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'secret'
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.route("/")
def hello():
return "Hello World!"
@app.route("/private")
@requires_auth #requires_auth decorator for basic auth
def private_page():
return "Hello I'm Private!!"
if __name__ == "__main__":
app.run()
Run the flask application
python app.py
Demo
Visit http://localhost:5000/private and you will be prompted for authentication. User name is admin and Password is secret.