Skip to content

Refactor auth decorators out of the shared library #5

@jeanetteclark

Description

@jeanetteclark

Currently, the @require_token and @require_scope decorators in dataone-auth are tightly coupled to Flask. They rely on Flask's global request object (to check request.method and extract headers) and flask.g (to store user context).

To make this library framework-agnostic and usable by both Flask and FastAPI, we need to strip the web-framework routing and request handling out of the shared code.

Changes needed

  1. Modify the shared library to expose a pure Python function, e.g., _validate_and_extract_claims(auth_header: str) -> tuple. This function should take the raw authorization header as a string and return the validated claims (or an error tuple).
  2. Delete the @require_token and @require_scope decorators from the shared library entirely.
  3. the important bit... Implement in Host Apps:
    • Flask: Include the @require_token and @require_scopes decorators inside the Flask (vegbank) codebase that extracts the header, calls the shared library function, and stores the result via _store_user_context which was also removed.
    • FastAPI: Create a standard FastAPI dependency (Depends(get_current_user)) in the FastAPI codebase that does the same thing.

Implementation in vegbank is pretty easy, just add the code back in that we stripped out here. FastAPI is a little different, but might look something like this:

def get_current_user(request: Request):
    auth_header = request.headers.get("Authorization")
    claims, error = _validate_and_extract_claims(auth_header)
    if error:
        error_dict, status_code = error
        raise HTTPException(status_code=status_code, detail=error_dict)
    return claims

@app.get("/workflows")
def get_workflows(user_claims: dict = Depends(get_current_user)):
    return {"message": "Hello", "user": user_claims}

Writing this down here mostly for future reference so I don't forget how the implementation is supposed to go later

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions