I am a little new to FastAPI in python. I am building an API backend framework that needs to have JWT token based authorization. Now, I know how to generate JWT tokens, but not sure how to integrate that with API methods in fast api in Python. Any pointers will be really appreciated.
Handle JWT tokens Create a variable ALGORITHM with the algorithm used to sign the JWT token and set it to "HS256" . Create a variable for the expiration of the token. Define a Pydantic Model that will be used in the token endpoint for the response. Create a utility function to generate a new access token.
I found certain improvements that could be made to the accepted answer:
get_token_auth_header
. Moreover, the generated docs end up being super clear and explanatory, with regards to authentication:JOSEError
, and print their message, avoiding catching specific exceptions, and writing custom messagesSample snippet: Where ...
/endpoints
- hello.py
- __init__.p
dependency.py
main.py
# dependency.py script
from jose import jwt
from jose.exceptions import JOSEError
from fastapi import HTTPException, Depends
from fastapi.security import HTTPBasicCredentials, HTTPBearer
security = HTTPBearer()
async def has_access(credentials: HTTPBasicCredentials = Depends(security)):
"""
Function that is used to validate the token in the case that it requires it
"""
token = credentials.credentials
try:
payload = jwt.decode(token, key='secret', options={"verify_signature": False,
"verify_aud": False,
"verify_iss": False})
print("payload => ", payload)
except JOSEError as e: # catches any exception
raise HTTPException(
status_code=401,
detail=str(e))
# main.py script
from fastapi import FastAPI, Depends
from endpoints import hello
from dependency import has_access
app = FastAPI()
# routes
PROTECTED = [Depends(has_access)]
app.include_router(
hello.router,
prefix="/hello",
dependencies=PROTECTED
)
# hello.py script
from fastapi import APIRouter
router = APIRouter()
@router.get("")
async def say_hi(name: str):
return "Hi " + name
By taking advantage of all the mentioned features, you end up building an API with security super fast :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With