Reputation: 41
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
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:
/token
endpoint where your user can exchange a username/password with a token, the token has usually an expirationIf 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