Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Flaskで Basic認証、Digest認証

More than 3 years have passed since last update.

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について調べる

msrks
Computer Scienceと物理が好きです
http://msrks.github.io
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away