[PYTHON] Flask Basic authentication

It is a premise of a project that has been Dokcerized once. Last time: Application development with Docker + Python + Flask

file organization

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

Addition of basic authentication function

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

python


from api.auth import auth

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

Add @ auth.login_required to routes that require basic authentication.

docker fix

docker-compose.yaml


version: '3'
services:
  api:
    container_name: tool-api
#abridgement
    environment: 
      BASIC_AUTH_USER: "user"
      BASIC_AUTH_PASSWORD: "password"

Set the eye path used in ʻauth.py` to an environment variable.

requirements.txt


#abridgement
flask_httpauth

Add the required modules.

Run

$ docker-compose up

Recommended Posts

Flask Basic authentication
Flask basic memo
BASIC authentication with Python bottle
flask
Dictionary attack on basic authentication
flask
[Python] Use Basic/Digest authentication with Flask
Numpy [Basic]
First Flask
Flask memo
Setting up Basic authentication using Python @Lambda
Basic commands
The day when basic authentication was added to the service operated by flask
Achieve Basic Authentication with CloudFront Lambda @ Edge with Python 3.8
Try slack OAuth authentication with flask (Slack API V2)
Incorporate JWT authentication into Python's Flask Web API
Send HTTP with Basic authentication header in Python
Flow to complete Slack authentication with Flask (Python)