我有一個 Python/Quart API REST 微服務,并且想要應用基于 API 密鑰的身份驗證。
執行此操作的常規方法是什么,存盤 API 密鑰的一般方法是什么?
包可以做到這一點還是我需要通過手動檢查“?api_key = asdfasdf”值等來實作我自己的?
我看到 quart_auth 具有基本身份驗證,但沒有基于 API 密鑰的身份驗證...
uj5u.com熱心網友回復:
沒有內置的方法來做到這一點(Quart 是不可知的,Quart-Auth 專注于 cookie 和基本身份驗證)。但是,以下內容適用于基于標頭的 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.args,request.cookies可用于代替request.headers.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436107.html
