简体   繁体   中英

Basic auth for Quart - python

I'm looking for using basic auth on Quart. I'm aware that quart-auth is available but it supports only cookies based authentication. Is there a way to use basic auth without resorting to use flask patch with Flask-BasicAuth?

This is how you can do it in Quart, (if you remove the async and await keywords and change quart to flask it will work for Flask as well).

from functools import wraps
from secrets import compare_digest

from quart import abort, current_app

def auth_required(func):

    @wraps(func)
    async def wrapper(*args, **kwargs):
        auth = request.authorization
        if (
            auth is not None and 
            auth.type == "basic" and
            auth.username == current_app.config["BASIC_AUTH_USERNAME"] and
            compare_digest(auth.password, current_app.config["BASIC_AUTH_PASSWORD"])
        ):
            return await func(*args, **kwargs)
        else:
            abort(401)

    return wrapper

# Usage

@auth_required
@app.route("/")
async def index():
     return ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM