Skip to content

Commit

Permalink
added Azure auth
Browse files Browse the repository at this point in the history
  • Loading branch information
mary-crkn committed Nov 9, 2024
1 parent 8ee458a commit e464cda
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 5 deletions.
32 changes: 32 additions & 0 deletions Azure_auth/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import os
from dotenv import load_dotenv
from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer

# Load .env file
load_dotenv()

# Read environment variables
BACKEND_CORS_ORIGINS = os.getenv("BACKEND_CORS_ORIGINS", "http://localhost:8000").split(',')
OPENAPI_CLIENT_ID = os.getenv("OPENAPI_CLIENT_ID", "")
APP_CLIENT_ID = os.getenv("APP_CLIENT_ID", "")
TENANT_ID = os.getenv("TENANT_ID", "")
SCOPE_DESCRIPTION = os.getenv("SCOPE_DESCRIPTION", "user_impersonation")
ADMIN_URL_EXTERNAL = os.getenv("ADMIN_URL_EXTERNAL", "")
AUTH_URL = os.getenv("AUTH_URL", "")
AUTH_SECRET = os.getenv("AUTH_SECRET", "")
ADMIN_PORT = os.getenv("ADMIN_PORT", "")

# Build necessary values
SCOPE_NAME = f'api://{APP_CLIENT_ID}/{SCOPE_DESCRIPTION}'
SCOPES = {
SCOPE_NAME: SCOPE_DESCRIPTION,
}
OPENAPI_AUTHORIZATION_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/authorize"
OPENAPI_TOKEN_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"

# Initialize Azure AD authentication scheme
azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
app_client_id=APP_CLIENT_ID,
tenant_id=TENANT_ID,
scopes=SCOPES,
)
13 changes: 11 additions & 2 deletions api/manifest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from fastapi import APIRouter,Depends,File,UploadFile,Request
from fastapi import APIRouter,Depends,File,UploadFile,Request,Security
from utils.upload_manifest import upload_manifest_backend

from Azure_auth.auth import azure_scheme
from Azure_auth.jwt_auth import jwt_auth
from utils.get_manifest_conn import get_manifest_conn

Expand All @@ -23,6 +23,15 @@ async def send_manifest(request:Request,
message = await upload_manifest_backend(request,file)
return message

@router.put("/file",dependencies=[Security(azure_scheme)])
async def update_manifest(request:Request,
file:UploadFile = File(...)

):
message = await upload_manifest_backend(request,file)
return message





Expand Down
11 changes: 9 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@
from api.manifest import router as manifest_router
from fastapi.responses import RedirectResponse
from utils.lifespan_handler import lifespan
from Azure_auth.auth import BACKEND_CORS_ORIGINS, OPENAPI_CLIENT_ID, SCOPE_NAME
app = FastAPI(

swagger_ui_oauth2_redirect_url='/oauth2-redirect',
swagger_ui_init_oauth={
'usePkceWithAuthorizationCodeGrant': True,
'clientId': OPENAPI_CLIENT_ID,
'scopes': SCOPE_NAME,
},
title="IIIF Presentation API",
description="Presentation API is to provide the information necessary to allow a rich, online viewing environment for compound digital objects to be presented to a human user, often in conjunction with the IIIF Image API",
summary="This is the sole purpose of the API and therefore descriptive information is given in a way that is intended for humans to read, but not semantically available to machines.",
Expand All @@ -25,7 +31,8 @@
'*'
]

app.add_middleware(
if BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
Expand Down
13 changes: 12 additions & 1 deletion utils/lifespan_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from fastapi import HTTPException
from swift_config.swift_config import get_swift_connection
from utils.settings import swift_user, swift_key, swift_auth_url, redis_url

from Azure_auth.auth import azure_scheme
#config logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
Expand All @@ -25,6 +25,8 @@ async def lifespan(app) -> AsyncGenerator[None,None]:
swift_session = aiohttp.ClientSession()

try:
#load OPENID config
await initialize_openid_config()

#swift authentication
swift_token, swift_storage_url = await initialize_swift()
Expand Down Expand Up @@ -54,6 +56,15 @@ async def lifespan(app) -> AsyncGenerator[None,None]:



async def initialize_openid_config():
"""
Load OpenID configuration on startup.
"""
try:
await azure_scheme.openid_config.load_config()
except Exception as e:
logger.error(f"Failed to load OpenID configuration: {e}")
raise

async def initialize_swift():
global swift_session,swift_storage_url,swift_token
Expand Down

0 comments on commit e464cda

Please sign in to comment.