Search code examples
pythonbasic-authenticationquart

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 ?


Solution

  • 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 ""