FastAPI is a modern web framework for building APIs in Python. It’s one of my personal favorite web frameworks as it has built-in support for OpenAPI specs (meaning you can write your backend code and generate everything from it) and it supports dependency injection.
In this post, we’ll briefly look at how FastAPI’s Depends works. We’ll then see why it applies so well to authentication and authorization. We’ll also contrast it with middleware, which is another common option for auth. Finally, we’ll look at some more advanced patterns for authorization in FastAPI.
What is Dependency Injection?
One of FastAPI’s more powerful features is its first class support for dependency injection. We have a longer guide here, but let’s look at a quick example of how it can be used.
Let’s say we are building a paginated API. Each API call may include a page_number and a page_size. Now, we could just create an API and take these parameters in directly:
@app.get("/things/") async def fetch_things(page_number: int = 0, page_size: int = 100): return db.fetch_things(page_number, page_size)
But, we probably want to add some validation logic so no one asks for page_number -1 or page_size 10,000,000.
@app.get("/things/") async def fetch_things(page_number: int = 0, page_size: int = 100): if page_number 100: raise HTTPException(status_code=400, detail="Page size can be at most 100") return db.fetch_things(page_number, page_size)
And this is... fine, but if we had 10 APIs or 100 APIs that all needed the same paging params, it’d get a bit tedious. This is where dependency injection comes in - we can move all this logic into a function and inject that function into our API:
async def paging_params_dep(page_number: int = 0, page_size: int = 100): if page_number 100: raise HTTPException(status_code=400, detail="Page size can be at most 100") return PagingParams(page_number, page_size) @app.get("/things/") async def fetch_things(paging_params: PagingParams = Depends(paging_params_dep)): return db.fetch_things(paging_params) @app.get("/other_things/") async def fetch_other_things(paging_params: PagingParams = Depends(paging_params_dep)): return db.fetch_other_things(paging_params)
This has some nice benefits:
Each route that takes in PagingParams is automatically validated and has default values.
It’s less verbose and error-prone than having the first line of each route be validate_paging_params(page_number, page_size)
This still works with FastAPI’s OpenAPI support - those parameters will show up in your OpenAPI specs.
What does this have to do with authentication?
It turns out, this is also a great way to model auth! Imagine you had a function like:
async def validate_token(token: str): try: # This could be JWT validation, looking up a session token in the DB, etc. return await get_user_for_token(token) except: return None
To hook this up to an API route, all we’d need to do is wrap it in a dependency:
async def require_valid_token_dep(req: Request): # This could also be a cookie, x-api-key header, etc. token = req.headers["Authorization"] user = await validate_token(token) if user == None: raise HTTPException(status_code=401, detail="Unauthorized") return user
And then all of our protected routes can add this dependency:
@app.get("/protected") async def do_secret_things(user: User = Depends(require_valid_token_dep)): # do something with the user
If the user provides a valid token, this route will run and user is set. Otherwise, a 401 will be returned.
Note: OpenAPI/Swagger does have first-class support for specifying auth tokens, but you have to use one of the dedicated classes for it. Instead of req.headers["Authorization"], you can use HTTPBearer(auto_error=False) from fastapi.security which returns an HTTPAuthorizationCredentials.
Middleware vs Depends for Auth
FastAPI, like most frameworks, has a concept of middleware. Your middleware can contain code that will run before and after a request. It can modify the request before the request gets to your route and it can modify the response before it’s returned to the user.
In many other frameworks, middleware is a really common place for authentication checks to take place. However, that’s often because the middleware is also tasked with “injecting” the user into the route. For example, a common pattern in Express is to do something like:
app.get("/protected", authMiddleware, (req, res) => { // req.user is set by the middleware // as there's no good way to pass in extra information into this route, // outside of the request });
Since FastAPI has a built-in concept of injection, you may not need to use middleware at all. I’d consider using middleware if you need to periodically “refresh” your auth tokens (to keep them alive) and set the response as a cookie.
In this case, you’ll want to use request.state to pass information from the middleware to the routes (and you can use a dependency to validate the request.state if you’d like).
Otherwise, I’d stick with using Depends as the user will be injected directly into your routes without needing to go through request.state.
Authorization - Multi-tenancy, Roles & Permissions
If we apply everything we learned so far, adding in multi-tenancy, roles or permissions can be pretty straightforward. Let’s say we have a unique subdomain for each of our customers, we can make a dependency for this subdomain:
async def tenant_by_subdomain_dep(request: Request) -> Optional[str]: # first we get the subdomain from the host header host = request.headers.get("host", "") parts = host.split(".") if len(parts) <p>We can combine this idea with our previous ideas and make a new “multi-tenant” dependency:<br> </p> <pre class="brush:php;toolbar:false">async def get_user_and_tenant_for_token( user: User = Depends(require_valid_token_dep), tenant: Tenant = Depends(tenant_by_subdomain_dep), ) -> UserAndTenant: is_user_in_tenant = await check_user_is_in_tenant(tenant, user) if is_user_in_tenant: return UserAndTenant(user, tenant) raise HTTPException(status_code=403, detail="Forbidden")
We can then inject this dependency into our routes:
@app.get("/protected") async def do_secret_things(user_and_tenant: UserAndTenant = Depends(get_user_and_tenant_for_token)): # do something with the user and tenant
And this ends up doing a few major things:
Checking that the user has a valid token
Checking that the user is making a request to a valid subdomain
Checking that the user should have access to that subdomain
If any of those invariants aren’t met - an error is returned and our route will never run. We can extend this to include other things like roles & permissions (RBAC) or making sure the user has a certain property set (active paid subscription vs no active subscription).
PropelAuth
At PropelAuth, we’re big fans of FastAPI. We have a FastAPI library that will enable you to set up authentication and authorization quickly - including SSO, Enterprise SSO / SAML, SCIM Provisioning, and more.
And it all works with dependencies like the ones you’ve seen above, e.g.:
@app.get("/") async def root(current_user: User = Depends(auth.require_user)): return {"message": f"Hello {current_user.user_id}"}
You can find out more here.
Summary
FastAPI's dependency injection provides a powerful way to handle authentication and authorization in web applications.
The Depends feature allows for clean, reusable code for validating tokens, checking user permissions, and handling multi-tenancy.
Compared to middleware, using dependencies for auth offers more flexibility and direct integration with route functions.
Complex authorization scenarios like multi-tenancy and role-based access control can be efficiently implemented using nested dependencies.
PropelAuth offers a FastAPI library that simplifies the implementation of advanced authentication and authorization features.
The above is the detailed content of FastAPI Auth with Dependency Injection. For more information, please follow other related articles on the PHP Chinese website!

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function