tokusumi / fastapi-cloudauth

Simple integration between FastAPI and cloud authentication services (AWS Cognito, Auth0, Firebase Authentication).
MIT License
333 stars 35 forks source link

Mock auth0 for tests #49

Open amitrahav opened 3 years ago

amitrahav commented 3 years ago

Request: adding documentation of mocking auth for tests.

I tried:


"""tests/test_templates.py"""
from fastapi.testclient import TestClient
from tests import auth_with_mocked_auth

client = TestClient(auth_with_mocked_auth())

def test_create_template():
    response = client.get("/templates/")
    assert response.status_code == 200

"""tests/__init__.py"""
def auth_with_mocked_auth():
    def override_auth_dependency():
        return {
             'iss': '<auth0 endoint>',
             'sub': 'auth0|<auth0 id>',
             'aud': [
                 '<endpoints>',
             ],
             'iat': <...>,
             'exp': <...>,
             'azp': '<...>,
             'scope': 'openid profile email read:current_user update:current_user_metadata',
             'permissions': [<...>]
        }

    app.dependency_overrides[auth] = override_auth_dependency()
    return app

Yet, getting 403 with details: "Not authenticated"

niekbruins commented 3 years ago

I had the same issue and i found this workaround:

def get_current_user(
    current_user: AccessUser = Depends(auth.claim(AccessUser)),
):
    return current_user

def get_read_scopes(
    scopes=Depends(auth.scope(["admin:read"])),
):
    return scopes

And then in the route

 @r.get(
    "/test",
    responses={404: {"description": "Not found"}},
    dependencies=[Depends(get_read_scopes)],
)
def get_contact_moment(
    current_user: AccessUser = Depends(get_current_user),
):

and then use app.dependency_overrides