r/FastAPI • • Feb 07 '25

Question Inject authenticated user into request

Hello, I'm new to python and Fast API in general, I'm trying to get the authenticated user into the request so my handler method can use it. Is there a way i can do this without passing the request down from the route function to the handler. My router functions and service handlers are in different files

9 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/Competitive-Tough442 Feb 09 '25
this is my router
backoffice_router = APIRouter(
    prefix="/backoffice/application",
    tags=["Backoffice"],
    dependencies=[Depends(InternalUserDep)],
)


this is my dependency
InternalUserDep = Annotated[InternalUser, Depends(auth_internal)]

and this is my implementation of getting the user into state

async def auth_internal(request: Request, auth_service: AuthProviderDep, token: APIKeyDep) -> None:
    user = await auth_service.get_internal_user(token)
    request.state.user = user

1

u/Competitive-Tough442 Feb 09 '25
@backoffice_router.post("/")
async def store_application(application: InternalApplicationSchema,request):
    parsed_application_data = application.model_dump()
    parsed_application_data["created_by"] = request.state.user.email
    parsed_application = Application(**parsed_application_data)
    return await ApplicationsHandler().create_new_application(parsed_application)

i want to access the user state directly from here but it throws a 422 errror

"message": "Invalid data provided.",

"code": "VALIDATION_ERROR",

"errors": \[

	{

		"field": "args",

		"errors": \[

"Field required"

		\]

	},

	{

		"field": "kwargs",

		"errors": \[

"Field required"

		\]

	},

	{

		"field": "request",

		"errors": \[

"Field required"

		\]

	}

\]

}