Last active
March 19, 2022 22:53
-
-
Save alfasin/9ed5440ea68530953640c9008a06e7eb to your computer and use it in GitHub Desktop.
A small example of a fastAPI server with JWT token
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
import jwt | |
from fastapi import FastAPI, Header | |
from pydantic import BaseModel | |
from typing import Optional | |
JWT_SECRET = "secret" # IRL we should NEVER hardcode the secret: it should be an evironment variable!!! | |
JWT_ALGORITHM = "HS256" | |
app = FastAPI() | |
class Person(BaseModel): | |
name: str | |
gender: Optional[str] = None | |
age: float | |
checked: Optional[bool] = None | |
@app.post("/") | |
async def root(person: Person, authorization: str = Header(None)): | |
try: | |
decoded = secure(authorization) | |
# here we can add code to check the user (by email) | |
# e.g. select the user from the DB and see its permissions | |
except: | |
return "Unauthorized Access!" | |
# in this example we'll simply return the person entity from the request body | |
# after adding a "checked" | |
person.checked = True | |
return person | |
def secure(token): | |
# if we want to sign/encrypt the JSON object: {"hello": "world"}, we can do it as follows | |
# encoded = jwt.encode({"hello": "world"}, JWT_SECRET, algorithm=JWT_ALGORITHM) | |
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=JWT_ALGORITHM) | |
# this is often used on the client side to encode the user's email address or other properties | |
return decoded_token |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment