-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-middleware.py
More file actions
41 lines (34 loc) · 1.47 KB
/
auth-middleware.py
File metadata and controls
41 lines (34 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from functools import wraps
from flask import request, jsonify
import jwt
def require_valid_token(public_key: str):
"""Decorator for endpoint authentication"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# Extract token from header
auth_header = request.headers.get('Authorization')
if not auth_header or not auth_header.startswith('Bearer '):
return jsonify({'error': 'Missing token'}), 401
token = auth_header.split(' ')[1]
try:
# Validate token
payload = jwt.decode(
token,
public_key,
algorithms=["ES256"]
)
# Check container binding if enforced
if payload.get('enforce_container_binding') == 'true':
container_id = request.headers.get('X-Container-ID')
if container_id != payload.get('container_id'):
return jsonify({'error': 'Container ID mismatch'}), 403
# Add payload to request context
request.jwt_payload = payload
except jwt.ExpiredSignatureError:
return jsonify({'error': 'Token expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'error': 'Invalid token'}), 401
return f(*args, **kwargs)
return decorated_function
return decorator