簡體   English   中英

我可以使用 FastAPI 生成動態 apiKey

[英]Can I generate dynamic apiKey using FastAPI

我正在使用 FastAPI 為機器學習模型創建 API。 我需要保護我的端點。 我目前正在使用 apiKey 進行身份驗證。 我在此鏈接之后實施了身份驗證:

到目前為止,我已經實現:


API_KEY = config('API_KEY')
API_KEY_NAME = config("API_KEY_NAME")
COOKIE_DOMAIN = config("COOKIE_DOMAIN")

api_key_query = APIKeyQuery(name=API_KEY_NAME, auto_error=False)
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
api_key_cookie = APIKeyCookie(name=API_KEY_NAME, auto_error=False)


async def get_api_key(
    api_key_query: str = Security(api_key_query),
    api_key_header: str = Security(api_key_header),
    api_key_cookie: str = Security(api_key_cookie),
):

    if api_key_query == API_KEY:
        return api_key_query
    elif api_key_header == API_KEY:
        return api_key_header
    elif api_key_cookie == API_KEY:
        return api_key_cookie
    else:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
        )

@app.get("/")
async def homepage():
    return "Welcome to the security test!"


@app.get("/logout")
async def route_logout_and_remove_cookie():
    response = RedirectResponse(url="/")
    response.delete_cookie(API_KEY_NAME, domain=COOKIE_DOMAIN)
    return response


@app.get("/secure_endpoint", tags=["test"])
async def get_open_api_endpoint(api_key: APIKey = Depends(get_api_key)):
    response = "How cool is this?"
    return response
    

@app.post('/api/model_pred')
async def face_detection(request: Request, image: UploadFile = File(...), api_key: APIKey = Depends(get_api_key)):
    pass

有什么方法可以通過生成動態 apiKeys 來實現身份驗證? 如果有人想使用我的端點,我可以生成一個唯一密鑰,他們可以使用它進行身份驗證。

有什么方法可以讓我的端點安全嗎?

您必須創建不同的端點以提供適當的(或多或少有限的)身份驗證工作流程,小型項目的非常基本的設置可能是:

  • 類似於/token端點,您的用戶可以使用令牌交換用戶名/密碼,令牌通常具有過期時間
  • 您需要存儲用戶到令牌(和到期)的映射,或者只存儲有效令牌的列表(通常是數據庫表,但對於小型項目可以是 memory 中的映射)
  • 根據您的列表檢查客戶端提供的令牌(通常在請求的 header 中)。

如果您不需要細粒度的授權,就像我在這里假設的那樣,您可以為所有用戶提供相同的用戶密碼; 然后告訴他們提交憑證以換取令牌,檢查令牌的有效性,接受/拒絕令牌或要求他們刷新它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM