如何在 Quart API 中使用 api 密钥认证?

How to use api key authentication with Quart API?

我有一个 Python/Quart API REST 微服务,想应用 API 基于密钥的身份验证。

执行此操作的常规方法是什么?存储 API 密钥的一般方法是什么?

包可以做到这一点还是我需要通过手动检查“?api_key=asdfasdf”值等来实现我自己的包?

我看到 quart_auth 有基本身份验证但没有 API 基于密钥的身份验证...

没有内置的方法来执行此操作(Quart 是不可知论者,Quart-Auth 专注于 cookie 和基本身份验证)。但是,以下内容适用于基于 header 的 API 键,

from quart import (
    current_app, 
    has_request_context, 
    has_websocket_context, 
    request, 
    websocket,
)
from werkzeug.exceptions import Unauthorized

def api_key_required(
    api_config_key: str = "API_KEY",
) -> Callable:
    """A decorator to restrict route access to requests with an API key. 

    This should be used to wrap a route handler (or view function) to
    enforce that only api key authenticated requests can access it. The
    key value is configurable via the app configuration with API_KEY key
    used by default. Note that it is important that this decorator be 
    wrapped by the route decorator and not vice, versa, as below.

    .. code-block:: python

        @app.route('/')
        @api_key_required()
        async def index():
            ...

    If the request is not authenticated a
    `werkzeug.exceptions.Unauthorized` exception will be raised.

    """

    def decorator(func: Callable) -> Callable:
        @wraps(func)
        async def wrapper(*args: Any, **kwargs: Any) -> Any:
            if has_request_context():
                api_key = request.headers.get("X-API-Key", "")
            elif has_websocket_context():
                api_key = websocket.headers.get("X-API-Key", "")
            else:
                raise RuntimeError("Not used in a valid request/websocket context")

            if (compare_digest(api_key, current_app.config[api_config_key])):
                return await current_app.ensure_async(func)(*args, **kwargs)
            else:
                raise Unauthorized()

        return wrapper

    return decorator

对于基于查询字符串或 cookie 的 API 键,可以使用 request.argsrequest.cookies 代替 request.headers