|
1 | 1 | import logging |
2 | 2 | from datetime import datetime, timedelta |
3 | | -from typing import Optional |
| 3 | +from typing import Optional, Union |
4 | 4 |
|
5 | 5 | from demo_project.core.config import settings |
6 | 6 | from fastapi import Depends |
| 7 | +from fastapi.security.api_key import APIKeyHeader |
7 | 8 |
|
8 | | -from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer |
| 9 | +from fastapi_azure_auth import MultiTenantAzureAuthorizationCodeBearer, SingleTenantAzureAuthorizationCodeBearer |
9 | 10 | from fastapi_azure_auth.exceptions import InvalidAuth |
10 | 11 | from fastapi_azure_auth.user import User |
11 | 12 |
|
@@ -49,10 +50,40 @@ async def __call__(self, tid: str) -> str: |
49 | 50 | # logic to find your allowed tenants and it's issuers here |
50 | 51 | # (This example cache in memory for 1 hour) |
51 | 52 | self.tid_to_iss = { |
52 | | - 'intility_tenant': 'intility_tenant', |
| 53 | + 'intility_tenant_id': 'https://login.microsoftonline.com/intility_tenant/v2.0', |
53 | 54 | } |
54 | 55 | try: |
55 | 56 | return self.tid_to_iss[tid] |
56 | 57 | except Exception as error: |
57 | 58 | log.exception('`iss` not found for `tid` %s. Error %s', tid, error) |
58 | 59 | raise InvalidAuth('You must be an Intility customer to access this resource') |
| 60 | + |
| 61 | + |
| 62 | +issuer_fetcher = IssuerFetcher() |
| 63 | + |
| 64 | +azure_scheme_auto_error_false = MultiTenantAzureAuthorizationCodeBearer( |
| 65 | + app_client_id=settings.APP_CLIENT_ID, |
| 66 | + scopes={ |
| 67 | + f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'User impersonation', |
| 68 | + }, |
| 69 | + validate_iss=True, |
| 70 | + iss_callable=issuer_fetcher, |
| 71 | + auto_error=False, |
| 72 | +) |
| 73 | + |
| 74 | + |
| 75 | +api_key_auth_auto_error_false = APIKeyHeader(name='TEST-API-KEY', auto_error=False) |
| 76 | + |
| 77 | + |
| 78 | +async def multi_auth( |
| 79 | + azure_auth: Optional[User] = Depends(azure_scheme_auto_error_false), |
| 80 | + api_key: Optional[str] = Depends(api_key_auth_auto_error_false), |
| 81 | +) -> Union[User, str]: |
| 82 | + """ |
| 83 | + Example implementation. |
| 84 | + """ |
| 85 | + if azure_auth: |
| 86 | + return azure_auth |
| 87 | + if api_key == 'JonasIsCool': |
| 88 | + return api_key |
| 89 | + raise InvalidAuth('You must either provide a valid bearer token or API key') |
0 commit comments