Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI create auth for all endpoints

Tags:

python

fastapi

I followed this documentation to setup up a single user: https://fastapi.tiangolo.com/advanced/security/http-basic-auth/

But I only get prompted for user/pass for that one end point, "/users/me".

How do I ensure that all endpoints are behind auth?

like image 798
ScipioAfricanus Avatar asked Mar 27 '26 18:03

ScipioAfricanus


1 Answers

You can configure FastAPI with a set of dependencies that needs to be resolved for any endpoint by giving the paramter directly when creating the FastAPI application (i.e. global dependencies):

security = HTTPBasic()

app = FastAPI(dependencies=[Depends(security)])

If you want some endpoints to be authenticated and some to be unauthenticated, you can create separate instances of APIRouter, then assign required dependencies to the one that require authentication:

unauthenticated_router = APIRouter()
authenticated_router = APIRouter(dependencies=[Depends(security)])

.. and then either include other routers under each (using .include_router) or register endpoints as you'd do with the app object - but instead use your two routers.

like image 98
MatsLindh Avatar answered Mar 30 '26 00:03

MatsLindh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!