@@ -28,25 +28,43 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
2828 signing_key = get_jwk_from_secret (SECRET_KEY )
2929 return instance .encode (to_encode , signing_key , alg = 'HS256' )
3030
31- def verify_token (credentials : HTTPAuthorizationCredentials = Depends ( security ) ) -> Dict :
31+ def verify_token (credentials : HTTPAuthorizationCredentials ) -> Dict :
3232 """Verify the JWT token from the Authorization header."""
33-
34- if credentials is None :
35- return None
33+
34+ if not credentials or not credentials .credentials :
35+ raise HTTPException (
36+ status_code = 401 ,
37+ detail = "No token provided" ,
38+ headers = {"WWW-Authenticate" : "Bearer" }
39+ )
40+
3641 token = credentials .credentials
3742 verifying_key = get_jwk_from_secret (SECRET_KEY )
3843 try :
3944 payload = instance .decode (token , verifying_key , do_time_check = True , algorithms = 'HS256' )
4045 return payload
41- except Exception :
42- raise HTTPException (status_code = 401 , detail = "Invalid or expired token" )
46+ except Exception as e :
47+ raise HTTPException (
48+ status_code = 401 ,
49+ detail = f"Invalid or expired token: { str (e )} " ,
50+ headers = {"WWW-Authenticate" : "Bearer" }
51+ )
4352
4453
4554def get_token_dependency (config : Dict ):
4655 """Return the token dependency if JWT is enabled, else a function that returns None."""
47-
56+
4857 if config .get ("security" , {}).get ("jwt_enabled" , False ):
49- return verify_token
58+ def jwt_required (credentials : HTTPAuthorizationCredentials = Depends (security )) -> Dict :
59+ """Enforce JWT authentication when enabled."""
60+ if credentials is None :
61+ raise HTTPException (
62+ status_code = 401 ,
63+ detail = "Authentication required. Please provide a valid Bearer token." ,
64+ headers = {"WWW-Authenticate" : "Bearer" }
65+ )
66+ return verify_token (credentials )
67+ return jwt_required
5068 else :
5169 return lambda : None
5270
0 commit comments