Prabin Nepal
Prabin Nepal

Reputation: 41

Can I generate dynamic apiKey using FastAPI

I am creating API for machine learning models using FastAPI. I need to secure my endpoints. I am currently using apiKey for authentication. 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? 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?

Upvotes: 2

Views: 1628

Answers (1)

tuned
tuned

Reputation: 1125

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
  • 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)
  • check the token provided by the client (usually in the header of the request) against your list.

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.

Upvotes: 1

Related Questions