44from urllib .request import urlopen
55
66import jwt
7+ from django .conf import settings
78from ninja .security import HttpBearer
89
910logger = logging .getLogger (__name__ )
1213
1314
1415class TokenValidator (HttpBearer ):
15- def __init__ (self ):
16- self .bypass_auth = os .getenv ("BYPASS_API_TOKEN_AUTH" , "false" ).lower () == "true"
17- self .api_audience = os .environ ["API_AUDIENCE" ]
18- self .tenant_id = os .environ ["TENANT_ID" ]
19- self .discovery_keys_url = (
20- "https://login.microsoftonline.com/"
21- + self .tenant_id
22- + "/discovery/v2.0/keys"
23- )
24- self .issuer_url = "https://sts.windows.net/" + self .tenant_id + "/"
25-
2616 def authenticate (self , request , token ) -> dict | None :
27- if self .bypass_auth :
17+ if self .bypass_authentication :
2818 logger .warning ("Authentication bypass is enabled." )
2919 return {"sub" : "bypass_user" }
3020
@@ -49,16 +39,16 @@ def _rsa_key(self, token) -> dict | None:
4939 "e" : key ["e" ],
5040 }
5141 except Exception :
52- logger .error ("Unable to parse authentication token." , exc_info = True )
42+ logger .exception ("Unable to parse authentication token." )
5343
5444 def _decode (self , token : str , rsa_key : dict ) -> dict | None :
5545 try :
5646 payload = jwt .decode (
5747 token ,
5848 rsa_key ,
5949 algorithms = ALLOWED_ALGORITHMS ,
60- audience = self . api_audience ,
61- issuer = self .issuer_url ,
50+ audience = os . getenv ( "API_AUDIENCE" ) ,
51+ issuer = f"https://sts.windows.net/ { self .tenant_id } /" ,
6252 )
6353 return payload
6454 except jwt .ExpiredSignatureError :
@@ -69,3 +59,15 @@ def _decode(self, token: str, rsa_key: dict) -> dict | None:
6959 logger .exception ("Token is invalid" )
7060 except Exception :
7161 logger .exception ("Unable to parse authentication token." )
62+
63+ @property
64+ def discovery_keys_url (self ) -> str :
65+ return f"https://login.microsoftonline.com/{ self .tenant_id } /discovery/v2.0/keys"
66+
67+ @property
68+ def tenant_id (self ) -> str | None :
69+ return os .getenv ("TENANT_ID" , "" )
70+
71+ @property
72+ def bypass_authentication (self ) -> bool :
73+ return getattr (settings , "BYPASS_API_TOKEN_AUTH" , False )
0 commit comments