Created
November 9, 2020 23:12
-
-
Save makupi/436248cc6377db0572150913a789d268 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import Security, Depends, FastAPI, HTTPException | |
from fastapi.security.api_key import APIKeyQuery, APIKeyCookie, APIKeyHeader, APIKey | |
from starlette.status import HTTP_403_FORBIDDEN | |
API_KEY_NAME = "access_token" | |
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) | |
app = FastAPI() | |
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("/secure-endpoint") | |
async def secure_endpoint(api_key: ApiKey = Depends(get_api_key)): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment