Flask で最低限のベーシック認証を導入する手順をまとめます。
認証対象となるルートにデコレータを付けるだけのシンプルな構成です。
手順
1. デコレータを定義する
requires_auth デコレータを用意し、リクエストヘッダの Authorization を検証します。
def requires_auth(f):
from functools import wraps
from flask import Response as res
username = 'USERNAME'
password = 'PASSWORD'
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not (auth.username == username and auth.password == password):
return res(
'Authentication required.', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
)
return f(*args, **kwargs)
return decorated
2. ルートにデコレータを適用する
from flask import render_template
@app.route("/", methods=['GET', 'POST'])
@requires_auth
def index():
return render_template("index.html")