def test_that_explicit_permission_overrides_are_applied(app, client): cred = HTTPBasicCredentials(username="******", password="******") security = FastAPISecurity() create_product_perm = security.user_permission("products:create") security.init_basic_auth([cred]) security.add_permission_overrides({"johndoe": ["products:create"]}) @app.post("/products") def create_product( user: User = Depends(security.user_holding(create_product_perm)), ): return {"ok": True} resp = client.post("/products", auth=("johndoe", "123")) assert resp.status_code == 200 assert resp.json() == {"ok": True}
def test_that_permission_overrides_can_be_an_exhaustable_iterator(app, client): cred = HTTPBasicCredentials(username="******", password="******") security = FastAPISecurity() create_product_perm = security.user_permission("products:create") security.init_basic_auth([cred]) overrides = iter(["products:create"]) security.add_permission_overrides({"johndoe": overrides}) @app.post("/products") def create_product( user: User = Depends(security.user_holding(create_product_perm)), ): return {"ok": True} # NOTE: Before v0.3.1, the second iteration would give a HTTP403, as the overrides # iterator had been exhausted on the first try. for _ in range(2): resp = client.post("/products", auth=("johndoe", "123")) assert resp.status_code == 200 assert resp.json() == {"ok": True}
if settings.basic_auth_credentials: security.init_basic_auth(settings.basic_auth_credentials) if settings.oidc_discovery_url: security.init_oauth2_through_oidc( settings.oidc_discovery_url, audiences=settings.oauth2_audiences, ) elif settings.oauth2_jwks_url: security.init_oauth2_through_jwks( settings.oauth2_jwks_url, audiences=settings.oauth2_audiences, ) security.add_permission_overrides(settings.permission_overrides or {}) logger = logging.getLogger(__name__) create_product_perm = security.user_permission("products:create") @app.get("/users/me") async def get_user_details(user: User = Depends(security.user_with_info)): """Return user details, regardless of whether user is authenticated or not""" return user.without_access_token() @app.get("/users/me/permissions", response_model=List[str]) def get_user_permissions(user: User = Depends( security.authenticated_user_or_401)):