Skip to content

Commit dacc7fa

Browse files
authored
Merge pull request developmentseed#10 from SIAnalytics/feat/auth-with-token
JWT logic modified. Token should be sent in parameters.
2 parents fdc092e + cca18c5 commit dacc7fa

File tree

3 files changed

+26
-18
lines changed

3 files changed

+26
-18
lines changed

src/titiler/application/titiler/application/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@
151151
)
152152

153153
if api_settings.jwt_secret:
154-
app.add_middleware(JWTAuthenticationMiddleware, secret=api_settings.jwt_secret)
154+
app.add_middleware(JWTAuthenticationMiddleware, secret=api_settings.jwt_secret, user_key="id")
155155

156156
if api_settings.debug:
157157
logging.basicConfig(level=logging.DEBUG)

src/titiler/application/titiler/application/settings.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""Titiler API settings."""
2-
2+
import os
33
from pydantic import field_validator
44
from pydantic_settings import BaseSettings, SettingsConfigDict
55

@@ -20,7 +20,7 @@ class ApiSettings(BaseSettings):
2020

2121
lower_case_query_parameters: bool = False
2222
fake_https: bool = False
23-
jwt_secret: str = ""
23+
jwt_secret: str = os.getenv("OVISION_TOKEN", "")
2424

2525
model_config = SettingsConfigDict(env_prefix="TITILER_API_", env_file=".env")
2626

src/titiler/core/titiler/core/middleware.py

+23-15
Original file line numberDiff line numberDiff line change
@@ -147,19 +147,18 @@ async def send_wrapper(message: Message):
147147
except:
148148
user = None
149149
if user:
150-
log['user'] = user
151-
log['status'] = message["status"]
150+
log["user"] = user
151+
log["status"] = message["status"]
152152

153153
if self.headers:
154-
log['res.headers'] = message["headers"]
154+
log["res.headers"] = message["headers"]
155155

156156
self.logger.debug(log)
157157
await send(message)
158158

159159
await self.app(scope, receive, send_wrapper)
160160

161161

162-
163162
class LowerCaseQueryStringMiddleware:
164163
"""Middleware to make URL parameters case-insensitive.
165164
taken from: https://github.com/tiangolo/fastapi/issues/826
@@ -212,9 +211,11 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
212211

213212

214213
class JWTAuthenticationMiddleware:
215-
"""Middleware to authentication with jwt"""
214+
"""Middleware for authentication with jwt"""
216215

217-
def __init__(self, app: ASGIApp, secret: str, user_key="user", algorithms: List[str]=None) -> None:
216+
def __init__(
217+
self, app: ASGIApp, secret: str, user_key="user", algorithms: List[str] = None
218+
) -> None:
218219
"""Init Middleware.
219220
220221
Args:
@@ -224,35 +225,42 @@ def __init__(self, app: ASGIApp, secret: str, user_key="user", algorithms: List[
224225
algorithms (List[str]): algorithms for decode jwt. default ["HS512"]
225226
"""
226227
if algorithms is None:
227-
algorithms = ["HS512"]
228+
algorithms = ["HS256"]
228229
from fastapi.security import HTTPBearer
230+
229231
self.app = app
230232
self.secret = secret
231233
self.http_bearer = HTTPBearer(bearerFormat="jwt", auto_error=False)
232234
self.algorithms = algorithms
233235
self.user_key = user_key
234236

235237
async def __call__(self, scope: Scope, receive: Receive, send: Send):
236-
async def response401(message: str="Not authenticated"):
237-
response = JSONResponse(content={"detail": message},
238-
status_code=starlette.status.HTTP_401_UNAUTHORIZED)
238+
async def response401(message: str = "Not authenticated"):
239+
response = JSONResponse(
240+
content={"detail": message},
241+
status_code=starlette.status.HTTP_401_UNAUTHORIZED,
242+
)
239243
await response(scope, receive, send)
244+
240245
"""Handle call."""
241246
if scope["type"] == "http":
242247
request = Request(scope)
243-
credentials = await self.http_bearer(request)
244-
if not credentials:
248+
249+
access_token = request.query_params.get("access_token")
250+
if not access_token:
245251
await response401("access token is required")
246252
return
247253
try:
248-
payload = jwt.decode(credentials.credentials, self.secret, algorithms=self.algorithms)
254+
payload = jwt.decode(
255+
access_token, self.secret, algorithms=self.algorithms
256+
)
249257
except jwt.DecodeError as e:
250258
await response401("unsupported token")
251259
except jwt.InvalidTokenError as e:
252260
await response401("invalid token")
253261
return
254262
user = payload[self.user_key]
255-
scope['auth'] = credentials.credentials
256-
scope['user'] = user
263+
scope["auth"] = access_token
264+
scope["user"] = user
257265

258266
await self.app(scope, receive, send)

0 commit comments

Comments
 (0)