root/
│
├── backend/
│ └── __init__.py
│ └── app.py # our FastAPI app
│ └── utils.py # Utility for JWT encoding/decoding
│ └── schemas.py # Pydantic models
│ └── database.py # Database connection
├── templates/
│ └── index.html # HTML template
└── .gitignore
└── pyproject.toml # Project configuration file
└── README.md
└── .env # Environment file, REMEMBER you have to create this!!
└── requirements.txt
└── venv/ # Virtual environment
Fire up your command prompt/terminal and type
cd FastAPI-JWT-Authentication
python -m venv fastapienv
fastapienv\Scripts\activate # on Windows
source fastapienv/bin/activate # on macOspip install "fastapi[standard]"
pip install -r requirements.txtIf you have the project setup on your local environment, here are the dependencies that you need to install for JWT authentication (assuming that you have a FastAPI project running):
pip install "python-jose[cryptography]" "passlib[bcrypt]" python-multipart from passlib.context import CryptContext
password_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def get_hashed_password(password: str) -> str:
return password_context.hash(password)
def verify_password(password: str, hashed_pass: str) -> bool:
return password_context.verify(password, hashed_pass)
JWT means "JSON Web Tokens". It's a standard way to codify a JSON object in a long dense string without spaces. It looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
It's not encrypted, so anyone could recover the information from the contents, but since it's signed, so when you receive a token that you issued, you can verify that it was you who issued it.
def create_access_token(subject: Union[str, Any], expires_delta: int = None)->str:
if expires_delta is not None:
expires_delta = datetime.utcnow() + expires_delta
else:
expires_delta = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {"exp": expires_delta,
"sub": str(subject)}
encoded_jwt = jwt.encode(to_encode,
SECRET_KEY,
ALGORITHM)
return encoded_jwt