article

Monday, March 20, 2023

FastAPI login with PyJWT token authentication

FastAPI login with PyJWT token authentication

Install Fastapi

https://github.com/tiangolo/fastapi

pip install fastapi
C:\fastAPI\jwt-auth>pip install fastapi
C:\fastAPI\jwt-auth>pip install "uvicorn[standard]"


Create main.py
jwt-auth/main.py
 
#jwt-auth/main.py
from fastapi import FastAPI
import jwt #pip install pyjwt https://pypi.org/project/PyJWT/
from pydantic import BaseModel
from fastapi.encoders import jsonable_encoder

SECRET_KEY = "cairocoders123456789"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 800

dummy_user = {
    "username": "cairocoders",
    "password": "123456ednalan",
}

app = FastAPI()

class Loginclass(BaseModel):
    username: str
    password: str
@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/login")
async def login_user(login_item: Loginclass):
    data = jsonable_encoder(login_item)
    if dummy_user['username'] == data['username'] and dummy_user['password'] == data['password']:
        encoded_jwt = jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)
        return {'token': encoded_jwt }
    else:
        return {'message': 'Login failed'}
install PyJWT
https://github.com/jpadilla/pyjwt

pip install PyJWT
C:\fastAPI\jwt-auth>pip install PyJWT

Rn C:\fastAPI\jwt-auth>uvicorn main:app --reload 

http://127.0.0.1:8000/docs

Related Post