Skip to content

Commit

Permalink
rebasing and adding in scope validation dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
swyatt7 committed Feb 6, 2024
1 parent f933587 commit ceea089
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
4 changes: 2 additions & 2 deletions python/across_api/across/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from fastapi import Depends, Query, Security

from ..base.api import app
from ..auth.api import ScopeAuthenticate
from ..auth.api import scopeauthorize
from .hello import Hello
from .resolve import Resolve
from .schema import HelloSchema, ResolveSchema
Expand Down Expand Up @@ -51,7 +51,7 @@ def hello(name: YourNameDep) -> HelloSchema:
@app.get(
"/secure_hello",
dependencies=[
Security(ScopeAuthenticate, scopes=["gcn.nasa.gov/kafka-public-consumer"])
Security(scopeauthorize, scopes=["gcn.nasa.gov/kafka-public-consumer"])
],
)
async def secure_hello(name: YourNameDep) -> HelloSchema:
Expand Down
31 changes: 27 additions & 4 deletions python/across_api/auth/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
from jose import jwt
from jose.exceptions import JWTError
import httpx # type: ignore
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi import Depends, HTTPException, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, SecurityScopes

from ..base.api import app
from .schema import VerifyAuth
Expand Down Expand Up @@ -77,10 +77,33 @@ async def claims(
raise HTTPException(status_code=401, detail=f"Authentication error: {e}")


JWTBearerDep = [Depends(claims)]
async def scopeauthorize(
security_scopes: SecurityScopes,
access_token: Annotated[dict, Depends(claims)],
):
# retrieve scopes from access token
scopes = access_token.get("scope", "")

# assuming the jwt scopes will be comma separated
token_scopes = scopes.split(",")

@app.get("/auth/verify", dependencies=[Security(ScopeAuthenticate, scopes=[])])
# validate the scopes
valid = False
if len(security_scopes.scopes):
valid = all(scope in security_scopes.scopes for scope in token_scopes)
else:
valid = True

# raise exception if user.role not in endpoint scope
if not valid:
raise HTTPException(
status_code=401,
detail="Bearer token scope(s) not in endpoint scope",
headers={"WWW-Authenticate": "Bearer"},
)


@app.get("/auth/verify", dependencies=[Security(scopeauthorize, scopes=[])])
async def verify_authentication() -> VerifyAuth:
"""Verify that the user is authenticated."""
return VerifyAuth()

0 comments on commit ceea089

Please sign in to comment.