|
| 1 | +from datetime import datetime, timedelta |
| 2 | +from typing import Optional, Tuple, Union |
| 3 | + |
| 4 | +import casbin |
| 5 | +import jwt |
| 6 | +import uvicorn |
| 7 | +from fastapi import FastAPI |
| 8 | +from starlette.authentication import ( |
| 9 | + AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials) |
| 10 | +from starlette.middleware.authentication import AuthenticationMiddleware |
| 11 | + |
| 12 | +from fastapi_authz import CasbinMiddleware |
| 13 | + |
| 14 | +JWT_SECRET_KEY = "secret" |
| 15 | +app = FastAPI() |
| 16 | + |
| 17 | + |
| 18 | +class JWTUser(BaseUser): |
| 19 | + def __init__(self, username: str, token: str, payload: dict) -> None: |
| 20 | + self.username = username |
| 21 | + self.token = token |
| 22 | + self.payload = payload |
| 23 | + |
| 24 | + @property |
| 25 | + def is_authenticated(self) -> bool: |
| 26 | + return True |
| 27 | + |
| 28 | + @property |
| 29 | + def display_name(self) -> str: |
| 30 | + return self.username |
| 31 | + |
| 32 | + |
| 33 | +class JWTAuthenticationBackend(AuthenticationBackend): |
| 34 | + |
| 35 | + def __init__(self, |
| 36 | + secret_key: str, |
| 37 | + algorithm: str = 'HS256', |
| 38 | + prefix: str = 'Bearer', |
| 39 | + username_field: str = 'username', |
| 40 | + audience: Optional[str] = None, |
| 41 | + options: Optional[dict] = None) -> None: |
| 42 | + self.secret_key = secret_key |
| 43 | + self.algorithm = algorithm |
| 44 | + self.prefix = prefix |
| 45 | + self.username_field = username_field |
| 46 | + self.audience = audience |
| 47 | + self.options = options or dict() |
| 48 | + |
| 49 | + @classmethod |
| 50 | + def get_token_from_header(cls, authorization: str, prefix: str) -> str: |
| 51 | + """Parses the Authorization header and returns only the token""" |
| 52 | + try: |
| 53 | + scheme, token = authorization.split() |
| 54 | + except ValueError as e: |
| 55 | + raise AuthenticationError('Could not separate Authorization scheme and token') from e |
| 56 | + |
| 57 | + if scheme.lower() != prefix.lower(): |
| 58 | + raise AuthenticationError(f'Authorization scheme {scheme} is not supported') |
| 59 | + return token |
| 60 | + |
| 61 | + async def authenticate(self, request) -> Union[None, Tuple[AuthCredentials, BaseUser]]: |
| 62 | + if "Authorization" not in request.headers: |
| 63 | + return None |
| 64 | + |
| 65 | + auth = request.headers["Authorization"] |
| 66 | + token = self.get_token_from_header(authorization=auth, prefix=self.prefix) |
| 67 | + try: |
| 68 | + payload = jwt.decode(token, key=self.secret_key, algorithms=self.algorithm, audience=self.audience, |
| 69 | + options=self.options) |
| 70 | + except jwt.InvalidTokenError as e: |
| 71 | + raise AuthenticationError(str(e)) from e |
| 72 | + return AuthCredentials(["authenticated"]), JWTUser(username=payload[self.username_field], token=token, |
| 73 | + payload=payload) |
| 74 | + |
| 75 | + |
| 76 | +enforcer = casbin.Enforcer('../examples/rbac_model.conf', '../examples/rbac_policy.csv') |
| 77 | +app.add_middleware(CasbinMiddleware, enforcer=enforcer) |
| 78 | + |
| 79 | +app.add_middleware(AuthenticationMiddleware, backend=JWTAuthenticationBackend(secret_key=JWT_SECRET_KEY)) |
| 80 | + |
| 81 | + |
| 82 | +def create_access_token(subject: str, expires_delta: timedelta = None) -> str: |
| 83 | + if expires_delta: |
| 84 | + expire = datetime.utcnow() + expires_delta |
| 85 | + else: |
| 86 | + expire = datetime.utcnow() + timedelta( |
| 87 | + minutes=60 |
| 88 | + ) |
| 89 | + to_encode = {"exp": expire, "username": subject} |
| 90 | + return jwt.encode(to_encode, JWT_SECRET_KEY, algorithm="HS256") |
| 91 | + |
| 92 | + |
| 93 | +@app.get('/') |
| 94 | +async def index(): |
| 95 | + return "If you see this, you have been authenticated." |
| 96 | + |
| 97 | + |
| 98 | +@app.get('/dataset1/protected') |
| 99 | +async def auth_test(): |
| 100 | + return "You must be alice to see this." |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == '__main__': |
| 104 | + print("alice:", create_access_token("alice", expires_delta=timedelta(minutes=60))) |
| 105 | + print("mark:", create_access_token("mark", expires_delta=timedelta(minutes=60))) |
| 106 | + uvicorn.run(app, debug=True) |
0 commit comments