|
9 | 9 | from jose import jwt
|
10 | 10 | from jose.exceptions import JWTError
|
11 | 11 | import httpx # type: ignore
|
12 |
| -from fastapi import Depends, HTTPException |
13 |
| -from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer |
| 12 | +from fastapi import Depends, HTTPException, Security |
| 13 | +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, SecurityScopes |
14 | 14 |
|
15 | 15 | from ..base.api import app
|
16 | 16 | from .schema import VerifyAuth
|
@@ -77,10 +77,26 @@ async def claims(
|
77 | 77 | raise HTTPException(status_code=401, detail=f"Authentication error: {e}")
|
78 | 78 |
|
79 | 79 |
|
80 |
| -JWTBearerDep = [Depends(claims)] |
| 80 | +async def scope_authorize( |
| 81 | + security_scopes: SecurityScopes, |
| 82 | + access_token: Annotated[dict, Depends(claims)], |
| 83 | +): |
| 84 | + # retrieve scopes from access token |
| 85 | + scopes = access_token.get("scope", "") |
81 | 86 |
|
| 87 | + # assuming the jwt scopes will be comma separated |
| 88 | + token_scopes = scopes.split(",") |
82 | 89 |
|
83 |
| -@app.get("/auth/verify", dependencies=JWTBearerDep) |
| 90 | + # raise exception if user.role not in endpoint scope |
| 91 | + if not all(scope in token_scopes for scope in security_scopes.scopes): |
| 92 | + raise HTTPException( |
| 93 | + status_code=401, |
| 94 | + detail="Bearer token scope(s) not in endpoint scope", |
| 95 | + headers={"WWW-Authenticate": "Bearer"}, |
| 96 | + ) |
| 97 | + |
| 98 | + |
| 99 | +@app.get("/auth/verify", dependencies=[Security(scope_authorize, scopes=[])]) |
84 | 100 | async def verify_authentication() -> VerifyAuth:
|
85 | 101 | """Verify that the user is authenticated."""
|
86 | 102 | return VerifyAuth()
|
0 commit comments