2

Im new to fastapi.

So created a basic api (login/register/view_items) for my requirements from a tutorial.

Project Structure

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:

USER ROUTER

My Item router contains:

ITEM ROUTER

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
Sunil Raj
  • 43
  • 4
  • Please include relevant code _as text_ in your question, as images are bad for accessibility - they can't be searched for, screenreaders generally don't handle them well, the reader has to switch back and forth and their content can't be copy/pasted. Your first question depends on your frontend application; generally you'd use a middleware that injects the authorization details into the request if available (for example with axios, if you're doing a JS frontend). Your second question can be implemented by having a dependency that requires a specific role for a user. – MatsLindh Mar 26 '23 at 10:36
  • 1
    For example as `user: User = Depends(user_with_access('edit'))`, `def user_with_access(key): def inner_function_that_verifies_against_key(): ..., return inner_function_that_verifies_against_key` - this will return a dependency function that verifies that the user has access to that specific role. – MatsLindh Mar 26 '23 at 10:38
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Сергей Кох Mar 26 '23 at 11:16

0 Answers0