15
13

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-httpauthを使って、FlaskでBasic認証を5分で実装する

Posted at

FlaskでBasic認証つけて、簡易的な管理ページを作ってみました。

flask-httpauthをインストール

$ pip install flask-httpauth

app.pyを編集

from flask import Flask
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
    "user_name": "password123",
}

@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, World"

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

これでbasic認証が現れるようになります。あっという間!!
image.png

AWS ElasticBeansTalksにデプロイするときには要注意!

これだけでEBにデプロイすると、Basic認証画面ポップは出てきますが、正しいユーザー名、パスワードを入力しても正常に通りません。 .ebextentions ディレクトリをapp.pyと同じディレクトリに作成して、その下に auth.config を作成してあげましょう。

auth.config
container_commands:
  01_wsgi_pass_headers:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

この状態で、デプロイするとBasic認証が正常に動くようになります。

15
13
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
15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?