Im new to fastapi.
So created a basic api (login/register/view_items) for my requirements from a tutorial.
Issue 1:
My login endpoint returns a Bearer token in json body once i login with valid creds. I have to manually add the token in headers [Auth Bearer] to view items. How could i append to the response headers, so user don't have to manually add.
Issue 2:
How can i control authorization (RBAC [admin,normal_user]), (signed in users can only view item endpoint and admin user can create items).
My User router contains:
My Item router contains:
Any suggestions to undertand auth model with users,roles and figure out is this project structure is a good strategy ; if i add a new feature , i need access control on it as well.
I tried this for authorization. But im unable to implement in the existing code. Not sure how this can be implemented in the current project structure.
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin
Additional:
@MatsLindh . This is relevant.
@router.post("/", response_model=ShowItem)
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
item = create_new_Item(item=item, db=db)
return item
This part is where i create item, but it is still accessible without authentication.
Also i want to make sure, there is no IDOR, even if its a signed in user, they should be using this resource for creating / modifying their own items. How can this be accomplished.
Snippet for auth :
def get_current_user_from_token(
token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
)
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
username: str = payload.get("sub")
print("username/email extracted is ", username)
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = get_user(username=username, db=db)
if user is None:
raise credentials_exception
return user