54
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flaskで Basic認証、Digest認証

Posted at

Flask拡張であるFlask-HTTPAuthを使うと、とても簡単に実現できます。

インストール

$ pip install flask-httpauth

Basic認証

  1. from flask_httpauth import HTTPBasicAuth する
  2. auth = HTTPBasicAuth()authインスタンスをつくる
  3. パスワードを確認する関数をつくる: @auth.get_passwordでデコレートする
  4. 認証したい URLを @auth.login_requiredでデコレートする
app.py
from flask import Flask
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
    "john": "hello",
    "susan": "bye"
}

@auth.get_password
def get_pw(username):
    if username in users:
        return users.get(username)
    return None

@app.route('/')
@auth.login_required
def index():
    return "Hello, %s!" % auth.username()

if __name__ == '__main__':
    app.run()

Digest認証

ユーザー名とパスワードを MD5でハッシュ化してからサーバーに送る。Basic認証で防げなかった盗聴や改竄への対策。

HTTPBasicAuthHTTPDigestAuthに変えるだけ。

app.py
from flask import Flask
from flask_httpauth import HTTPDigestAuth

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key here'
auth = HTTPDigestAuth()

users = {
    "john": "hello",
    "susan": "bye"
}

@auth.get_password
def get_pw(username):
    if username in users:
        return users.get(username)
    return None

@app.route('/')
@auth.login_required
def index():
    return "Hello, %s!" % auth.username()

if __name__ == '__main__':
    app.run()

ToDo: pathlib, itsdangerousについて調べる

54
47
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
54
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?