简体   繁体   English

我可以使用 FastAPI 生成动态 apiKey

[英]Can I generate dynamic apiKey using FastAPI

I am creating API for machine learning models using FastAPI.我正在使用 FastAPI 为机器学习模型创建 API。 I need to secure my endpoints.我需要保护我的端点。 I am currently using apiKey for authentication.我目前正在使用 apiKey 进行身份验证。 I implemented authentication following this link :我在此链接之后实施了身份验证:

So far I have implemented:到目前为止,我已经实现:


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

Is there any way I can implement authentication by generating dynamic apiKeys?有什么方法可以通过生成动态 apiKeys 来实现身份验证? If someone wants to use my endpoint, I can generate a unique key and they can use it for authentication.如果有人想使用我的端点,我可以生成一个唯一密钥,他们可以使用它进行身份验证。

Is there any method I can implement to make my endpoints secure?有什么方法可以让我的端点安全吗?

You have to create different endpoints to provide a proper (more or less limited) authentication workflow , a very basic setup for small projects could be:您必须创建不同的端点以提供适当的(或多或少有限的)身份验证工作流程,小型项目的非常基本的设置可能是:

  • something like a /token endpoint where your user can exchange a username/password with a token, the token has usually an expiration类似于/token端点,您的用户可以使用令牌交换用户名/密码,令牌通常具有过期时间
  • you need to store a mapping of user to tokens (and expirations), or just store a list of valid tokens (usually is a database table but can be a mapping in memory for small projects)您需要存储用户到令牌(和到期)的映射,或者只存储有效令牌的列表(通常是数据库表,但对于小型项目可以是 memory 中的映射)
  • check the token provided by the client (usually in the header of the request) against your list.根据您的列表检查客户端提供的令牌(通常在请求的 header 中)。

If you don't have the need for fine-grained authorization, as I assume here, you can just provide same user-password to all your users;如果您不需要细粒度的授权,就像我在这里假设的那样,您可以为所有用户提供相同的用户密码; then tell them to submit the credentials in exchange for a token, check the validity for the token, accept/reject the token or ask for them to refresh it.然后告诉他们提交凭证以换取令牌,检查令牌的有效性,接受/拒绝令牌或要求他们刷新它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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