I tried to work with jwt auth using fastapi and encountered one problem
from typing import Annotated
from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jwt import PyJWTError
from sqlalchemy.ext.asyncio import AsyncSession
from exception.errors import BAD_CREDENTIALS
from moduls.utils import decode_jwt
from sql_app.db import get_async_session
from sql_app.crud import get_user_by_email
from sql_app.models import Users
CurrentSessionDep = Annotated[AsyncSession, Depends(get_async_session)]
async def get_current_user(
token: Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer(scheme_name="Users"))],
session: CurrentSessionDep) -> Users:
try:
jwt_data = decode_jwt(
token=token.credentials
)
except PyJWTError:
raise BAD_CREDENTIALS
if jwt_data.issuer != "user":
raise BAD_CREDENTIALS
user = await get_user_by_email(
email=jwt_data.email,
session=session
)
if not user:
raise BAD_CREDENTIALS
return user
CurrentUserDep = Annotated[Users, Depends(get_current_user)]
this is code defines a dependency get_current_user
that retrieves the current user based on the provided JWT token. The user is fetched from the database using SQLAlchemy. If the token is invalid or the user doesn’t exist, it raises a BAD_CREDENTIALS
exception. This setup ensures that only authenticated users with valid tokens can access certain routes in your API.
below api which works with
@router.get(
path="/me",
name="Get info about logged user",
response_model_exclude_none=True, response_model=schemas.UserRead, response_description="Info about logged user")
async def show_user(current_user: CurrentUserDep):
return current_user
However, I get 403 error this is in /docs
and I got jwt token before:
/login
I tried to search information about it, but couldn’t find
pls help
I tried to find the problem in other functions that depend, but they passed any checks (decode_jwt
etc.), I thought that in /docs
this does not work, because I don’t know why my version does not work
mitty is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.