Basic Authentication

Django

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:

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

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:

# 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.

' '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.

Download