- HTTPBasicAuth
- flask_httpauth
- werkzeug.security
- generate_password_hash
- check_password_hash
Flask Simple Authentication + test
examples/flask/simple_auth/app.py
from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("nhoj"), "jane": generate_password_hash("enaj") } @app.route("/") def hello(): return "Hello World!" @auth.verify_password def verify_password(username, password): if username in users: return check_password_hash(users.get(username), password) return False @app.route("/admin") @auth.login_required def admin(): return "Hello Admin"
examples/flask/simple_auth/test_app.py
import app import base64 def test_app(): web = app.app.test_client() rv = web.get('/') assert rv.status == '200 OK' assert rv.data == b'Hello World!' def test_admin_unauth(): web = app.app.test_client() rv = web.get('/admin') assert rv.status == '401 UNAUTHORIZED' assert rv.data == b'Unauthorized Access' assert 'WWW-Authenticate' in rv.headers assert rv.headers['WWW-Authenticate'] == 'Basic realm="Authentication Required"' def test_admin_auth(): web = app.app.test_client() credentials = base64.b64encode(b'john:nhoj').decode('utf-8') rv = web.get('/admin', headers={ 'Authorization': 'Basic ' + credentials }) assert rv.status == '200 OK' assert rv.data == b'Hello Admin'