Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to secure fastapi API endpoint with JWT Token based authorization?

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.

like image 889
Aditya Bhattacharya Avatar asked Jul 20 '20 11:07

Aditya Bhattacharya


People also ask

How do I use JWT token in FastAPI?

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.


1 Answers

I found certain improvements that could be made to the accepted answer:

  • If you choose to use the HTTPBearer security schema, the format of the Authorization header content is automatically validated, and there is no need to have a function like the one in the accepted answer, get_token_auth_header. Moreover, the generated docs end up being super clear and explanatory, with regards to authentication:

enter image description here

  • When you decode the token, you can catch all exceptions that are descendants of the class JOSEError, and print their message, avoiding catching specific exceptions, and writing custom messages
  • Bonus: in the jwt decode method, you can specify what claims you want to ignore, given the fact you don't wanna validate them

Sample 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 :)

like image 62
onofricamila Avatar answered Oct 09 '22 22:10

onofricamila