Exploring Advanced Features in FastAPI: Role-Based Access Control with Dependency Injection and User Roles

Posted by

FastAPI Beyond CRUD Part 13 – Role-Based Access Control Using Dependency Injection (Add User Roles)

FastAPI Beyond CRUD Part 13 – Role-Based Access Control Using Dependency Injection (Add User Roles)

Role-based access control is a security measure that restricts system access based on the roles of individual users within an organization. In this tutorial, we will be adding user roles to our FastAPI application using dependency injection.

Step 1: Create User Roles

First, we need to define the different user roles that will be available in our application. This can be done by creating an Enum class in Python:


from enum import Enum

class UserRole(Enum):
    ADMIN = 'admin'
    USER = 'user'
    GUEST = 'guest'
    

Step 2: Add User Role Field to User Model

Next, we need to add a user_role field to our User model in the database. We can do this by updating our User model class:


from pydantic import BaseModel
from .user_roles import UserRole

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

    class Config:
        orm_mode = True
    

Step 3: Create Dependency for User Role

Now, we need to create a dependency that will check the user’s role before allowing access to certain endpoints. This can be done by creating a new function that takes the current user’s role as a parameter:


from fastapi import HTTPException, Depends
from .user_roles import UserRole

def check_user_role(user_role: UserRole = Depends()):
    if user_role != UserRole.ADMIN:
        raise HTTPException(status_code=403, detail="Permission denied")
        return user_role
    

Step 4: Protect Endpoints with User Role Dependency

Finally, we can protect our endpoints by adding the check_user_role dependency as a parameter in the endpoint function:


from fastapi import APIRouter
from .user_model import User
from .user_roles import UserRole
from .user_role_dependency import check_user_role

router = APIRouter()

@router.get("/admin_page")
async def admin_page(user: User = Depends(check_user_role)):
    return {"message": "Welcome, Admin!"}
    

By following these steps, we have successfully added user roles to our FastAPI application using dependency injection. This will help improve the security and access control of our application, ensuring that only authorized users have access to certain endpoints.

0 0 votes
Article Rating

Leave a Reply

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@SsaliJonathan
2 days ago

Hey guys, How do you feel about our progress into the series, Kindly let me know in the comment section. Also, please click the like button.

@suen-tech
2 days ago

I was waiting
Thank you @Jonathan
This part about access control (JWT, Revoking Tokens, Role-base access) are very interesting for me.
The logic and progression are well thought
Just keep it going 😃

2
0
Would love your thoughts, please comment.x
()
x