Niansuh commited on
Commit
76e848a
·
verified ·
1 Parent(s): 4f4f8e4

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +27 -9
main.py CHANGED
@@ -16,9 +16,9 @@ from slowapi import Limiter, _rate_limit_exceeded_handler
16
  from slowapi.util import get_remote_address
17
  from slowapi.errors import RateLimitExceeded
18
  from slowapi.middleware import SlowAPIMiddleware
19
- from fastapi import FastAPI, HTTPException, Request, Depends, Header, Security
20
  from fastapi.responses import StreamingResponse, JSONResponse, RedirectResponse
21
- from fastapi.security.api_key import APIKeyHeader
22
  from pydantic import BaseModel
23
 
24
  from aiohttp import ClientSession, ClientTimeout, ClientError
@@ -80,24 +80,42 @@ if not API_KEYS or API_KEYS == ['']:
80
  logger.error("No API keys found. Please set the API_KEYS environment variable.")
81
  raise Exception("API_KEYS environment variable not set.")
82
 
83
- # Define API key security
84
- API_KEY_NAME = "X-API-Key"
85
- api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
86
 
87
- async def get_api_key(api_key: str = Security(api_key_header)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  if not api_key:
89
- logger.warning("API key missing")
90
  raise HTTPException(
91
  status_code=401,
92
  detail="API key missing",
93
- headers={"WWW-Authenticate": "API Key"},
94
  )
95
  if api_key not in API_KEYS:
96
  logger.warning(f"Invalid API key: {api_key}")
97
  raise HTTPException(
98
  status_code=403,
99
  detail="Invalid API key",
100
- headers={"WWW-Authenticate": "API Key"},
101
  )
102
  return api_key
103
 
 
16
  from slowapi.util import get_remote_address
17
  from slowapi.errors import RateLimitExceeded
18
  from slowapi.middleware import SlowAPIMiddleware
19
+ from fastapi import FastAPI, HTTPException, Request, Depends, Security
20
  from fastapi.responses import StreamingResponse, JSONResponse, RedirectResponse
21
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
22
  from pydantic import BaseModel
23
 
24
  from aiohttp import ClientSession, ClientTimeout, ClientError
 
80
  logger.error("No API keys found. Please set the API_KEYS environment variable.")
81
  raise Exception("API_KEYS environment variable not set.")
82
 
83
+ # Define API key security using HTTPBearer (Bearer token)
84
+ security = HTTPBearer()
 
85
 
86
+ async def get_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
87
+ """
88
+ Dependency to extract and validate the API key from the Authorization header.
89
+ Expects the header in the format: Authorization: Bearer YOUR_API_KEY
90
+ """
91
+ if not credentials:
92
+ logger.warning("Authorization header missing")
93
+ raise HTTPException(
94
+ status_code=401,
95
+ detail="Authorization header missing",
96
+ headers={"WWW-Authenticate": "Bearer"},
97
+ )
98
+ if credentials.scheme.lower() != "bearer":
99
+ logger.warning(f"Invalid authentication scheme: {credentials.scheme}")
100
+ raise HTTPException(
101
+ status_code=401,
102
+ detail="Invalid authentication scheme. Expected 'Bearer'.",
103
+ headers={"WWW-Authenticate": "Bearer"},
104
+ )
105
+ api_key = credentials.credentials
106
  if not api_key:
107
+ logger.warning("API key missing in Authorization header")
108
  raise HTTPException(
109
  status_code=401,
110
  detail="API key missing",
111
+ headers={"WWW-Authenticate": "Bearer"},
112
  )
113
  if api_key not in API_KEYS:
114
  logger.warning(f"Invalid API key: {api_key}")
115
  raise HTTPException(
116
  status_code=403,
117
  detail="Invalid API key",
118
+ headers={"WWW-Authenticate": "Bearer"},
119
  )
120
  return api_key
121