How to authenticate user with fastapi python?

by cali_green , in category: Javascript , 12 days ago

How to authenticate user with fastapi python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 11 days ago

@cali_green 

FastAPI provides several ways to authenticate users, including API key authentication, OAuth2, JWT tokens, and more. Here's a simple example of how to authenticate a user with JWT tokens in FastAPI:

  1. First, install the necessary packages:
1
pip install fastapi[all] python-jose[cryptography]


  1. Create a JWT token helper function to encode and decode tokens:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from jose import JWTError, jwt
from datetime import datetime, timedelta
from typing import Optional

SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def decode_access_token(token: str):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except JWTError:
        return None


  1. Create a login route that generates a JWT token:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    username: str
    password: str

@app.post("/login")
def login(user: User):
    if user.username == "admin" and user.password == "password":
        access_token = create_access_token(data={"sub": user.username})
        return {"access_token": access_token, "token_type": "bearer"}
    else:
        raise HTTPException(status_code=401, detail="Invalid credentials")


  1. Create a protected route that requires a valid JWT token:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")

@app.get("/protected")
def protected_route(token: str = Depends(oauth2_scheme)):
    payload = decode_access_token(token)
    if payload is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
    return {"message": "Hello, World!", "username": payload.get("sub")}


  1. Run the FastAPI app and test the login and protected routes using a tool like Postman or curl.


This is just a basic example of how to authenticate users with JWT tokens in FastAPI. You can customize the authentication logic and token expiration settings to fit your specific requirements.