3
2

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 3 years have passed since last update.

Flask Basic認証

Posted at

一度Dokcerizeしてあるプロジェクト前提になってます。
前回:Docker + Python + Flaskでアプリケーション開発

ファイル構成

├── api
|   └── auth.api
├── requirements.txt
└── docker-compose.yaml

Basic認証機能の追加

auth.py
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
import os

auth = HTTPBasicAuth()

users = {
  os.getenv("BASIC_AUTH_USER"): generate_password_hash(os.getenv("BASIC_AUTH_PASSWORD"))
}

@auth.verify_password
def verify_password(username, password):
    if username in users:
        return check_password_hash(users.get(username), password)
    return False
from api.auth import auth

# 省略
@route('/')
@auth.login_required
def add():
# 省略

basic認証が必要なルーティングに@auth.login_requiredを追加します。

dockerの修正

docker-compose.yaml
version: '3'
services:
  api:
    container_name: tool-api
# 省略
    environment: 
      BASIC_AUTH_USER: "user"
      BASIC_AUTH_PASSWORD: "password"

auth.pyで使うアイパスを環境変数に設定します。

requirements.txt
# 省略
flask_httpauth

必要なモジュールを追加します。

実行

$ docker-compose up
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?