Merge pull request #1469 from unclecode/fix/docker-jwt

Fix(auth): Fixed Docker JWT authentication
This commit is contained in:
Nasrin
2025-09-04 15:00:15 +08:00
committed by GitHub
2 changed files with 28 additions and 10 deletions

View File

@@ -28,25 +28,43 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
signing_key = get_jwk_from_secret(SECRET_KEY) signing_key = get_jwk_from_secret(SECRET_KEY)
return instance.encode(to_encode, signing_key, alg='HS256') return instance.encode(to_encode, signing_key, alg='HS256')
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> Dict: def verify_token(credentials: HTTPAuthorizationCredentials) -> Dict:
"""Verify the JWT token from the Authorization header.""" """Verify the JWT token from the Authorization header."""
if credentials is None: if not credentials or not credentials.credentials:
return None raise HTTPException(
status_code=401,
detail="No token provided",
headers={"WWW-Authenticate": "Bearer"}
)
token = credentials.credentials token = credentials.credentials
verifying_key = get_jwk_from_secret(SECRET_KEY) verifying_key = get_jwk_from_secret(SECRET_KEY)
try: try:
payload = instance.decode(token, verifying_key, do_time_check=True, algorithms='HS256') payload = instance.decode(token, verifying_key, do_time_check=True, algorithms='HS256')
return payload return payload
except Exception: except Exception as e:
raise HTTPException(status_code=401, detail="Invalid or expired token") raise HTTPException(
status_code=401,
detail=f"Invalid or expired token: {str(e)}",
headers={"WWW-Authenticate": "Bearer"}
)
def get_token_dependency(config: Dict): def get_token_dependency(config: Dict):
"""Return the token dependency if JWT is enabled, else a function that returns None.""" """Return the token dependency if JWT is enabled, else a function that returns None."""
if config.get("security", {}).get("jwt_enabled", False): if config.get("security", {}).get("jwt_enabled", False):
return verify_token def jwt_required(credentials: HTTPAuthorizationCredentials = Depends(security)) -> Dict:
"""Enforce JWT authentication when enabled."""
if credentials is None:
raise HTTPException(
status_code=401,
detail="Authentication required. Please provide a valid Bearer token.",
headers={"WWW-Authenticate": "Bearer"}
)
return verify_token(credentials)
return jwt_required
else: else:
return lambda: None return lambda: None

View File

@@ -38,8 +38,8 @@ rate_limiting:
# Security Configuration # Security Configuration
security: security:
enabled: false enabled: false
jwt_enabled: false jwt_enabled: false
https_redirect: false https_redirect: false
trusted_hosts: ["*"] trusted_hosts: ["*"]
headers: headers: