0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask でベーシック認証をシンプルに実装する

Posted at

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")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?