How a website recognises a user
Authentication answers the question “who is this?”, authorisation answers “what are they allowed to do?”. We look at storing passwords, sessions and protected pages.
Passwords are stored only as a hash
A hash is an irreversible fingerprint. If the database is stolen, it contains no real passwords.
from werkzeug.security import check_password_hash, generate_password_hash
stored = generate_password_hash("secret123", method="pbkdf2:sha256")
print("Stored in the database:", stored[:40] + "...")
print("Correct password:", check_password_hash(stored, "secret123"))
print("Wrong password:", check_password_hash(stored, "qwerty"))
print("Two hashes differ:", stored != generate_password_hash("secret123", method="pbkdf2:sha256"))
Hashes of the same password differ because of a random “salt”, so identical passwords do not look the same in the database. A plain md5 or sha256 without salt and slowing down is not suitable for passwords. In a real application you can leave out the method: the library picks a strong default.
Session: how a site remembers your login
HTTP does not remember earlier requests. After you log in, the server gives the browser a cookie, and the browser attaches it to the next requests.
from functools import wraps
from flask import Flask, abort, redirect, request, session, url_for
from werkzeug.security import check_password_hash, generate_password_hash
app = Flask(__name__)
app.secret_key = "for-the-example-only" # in a real project, read it from an environment variable
USERS = {"ernar": generate_password_hash("secret123", method="pbkdf2:sha256")}
def login_required(view):
@wraps(view)
def wrapper(*args, **kwargs):
if "user" not in session:
return redirect(url_for("login"))
return view(*args, **kwargs)
return wrapper
@app.route("/login", methods=["POST"])
def login():
name = request.form.get("name", "")
stored = USERS.get(name)
if stored is None or not check_password_hash(stored, request.form.get("password", "")):
abort(401)
session["user"] = name
return redirect(url_for("profile"))
@app.route("/logout", methods=["POST"])
def logout():
session.clear()
return redirect(url_for("login"))
@app.route("/profile")
@login_required
def profile():
return f"Hello, {session['user']}!"
client = app.test_client()
print("Not logged in:", client.get("/profile").status_code)
print("Wrong password:", client.post("/login", data={"name": "ernar", "password": "x"}).status_code)
client.post("/login", data={"name": "ernar", "password": "secret123"})
print("After login:", client.get("/profile").text)
client.post("/logout")
print("After logout:", client.get("/profile").status_code)
What to watch out for
- A Flask session is signed with
secret_keybut not encrypted: do not keep secrets in it. - A wrong username and a wrong password get the same response, so nobody can find out which usernames exist.
- Logout is done with POST, so it cannot be triggered by a simple link on another site.
- On a real site, login must work only over HTTPS, and it is worth limiting the number of attempts.
Authentication in Django
Django already has users, password hashing, sessions and ready login pages.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")),
]
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def profile(request):
return render(request, "profile.html", {"user": request.user})
LOGIN_URL = "login"
LOGIN_REDIRECT_URL = "profile"
LOGOUT_REDIRECT_URL = "login"
You create the login template yourself: templates/registration/login.html. In current Django versions logout works only with POST, so make it a form with a button, not a link.
Access rights
After login it is important to check that the user works only with their own data.
A common mistake is to check only the login itself. If the address /tasks/5/delete is open to anyone logged in, someone else's task can be deleted just by changing the number. Always check the owner on the server:
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from .models import Task
@login_required
@require_POST
def delete_task(request, pk):
task = get_object_or_404(Task, pk=pk, owner=request.user)
task.delete()
return redirect("index")
Sources
Links checked on .
Next: REST API
A server can return not only pages but data too.