-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIdcsClient.py
1981 lines (1722 loc) · 77.9 KB
/
IdcsClient.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import base64
import requests
import time
import jwt
import json
from six.moves.urllib.parse import urlparse
from six.moves import urllib
import six
from Constants import Constants
import logging
from cryptography import x509
from cryptography.hazmat.backends import default_backend
import simplejson as json
import re
from lruttl import LRUCache
import warnings
import functools
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
@functools.wraps(func)
def deprecatedWarning(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning,
stacklevel=2)
warnings.simplefilter('default', DeprecationWarning) # reset filter
return func(*args, **kwargs)
return deprecatedWarning
class MetadataManager:
"""
This class provide methods to retrieve and manage the metadata for a tenant.
"""
def __init__(self, options, tenant = None):
"""
Default Constructor
:param options: A Dictionary containing BaseUrl, ClientId, and ClientSecret
"""
self.options = options
if tenant is not None:
self.tenant = tenant
else:
self.tenant = Utils.getTenant(self.options)
self.logger = Utils.getLogger(options)
def getMetaData(self):
"""
It returns the metadata as a JSON object.
The tenant for which metadata is returned is determined from the BaseUrl present in options
:return: JSON Object of tenant's metadata
"""
tenant = self.tenant
if tenant.lower() in CacheManager.metadata:
self.logger.debug("Metadata found in cache. Checking for expiry.")
md = CacheManager.metadata[tenant.lower()]
if md.getExpiry() > round(time.time()):
self.logger.debug("Metadata not expired. Returning from cache.")
return CacheManager.metadata[tenant.lower()]
self.logger.debug("Metadata expired. Going to Fetch new metadata.")
if Constants.BASE_URL not in self.options:
raise ValueError("BaseUrl is missing in required options for fetching Metadata.")
url = self.options[Constants.BASE_URL]
url += Constants.DISCOVERY_PATH
self.logger.debug("Going to fetch metadata from %s", url)
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.get(url, verify=verify)
if response.status_code == 200 :
md = response.json()
ret = Metadata(md)
CacheManager.metadata[tenant.lower()] = ret
self.logger.debug("Metadata fetch successful. Persisting in cache and returning.")
return ret
self.logger.error("Unable to fetch Metadata. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch Metadata. Response text server %s", response.text)
raise IdcsException("Failed to fetch Metadata", response)
class AccessTokenManager:
"""
This class provide methods to fetch and manage access token to perform operations like fetching user details, jwk
"""
def __init__(self, options):
"""
Default Constructor
:param options: A Dictionary containing BaseUrl, ClientId, and ClientSecret
"""
self.options = options
self.logger = Utils.getLogger(options)
def getAccessToken(self):
"""
This method returns a access token for urn:opc:idm:__myscopes__ using client credentials given in options
:return: Access Token for scope urn:opc:idm:__myscopes__
"""
tenant = Utils.getTenant(self.options)
if tenant.lower() in CacheManager.tokens:
self.logger.debug("Access Token found in cache. Going to check expiry.")
token = CacheManager.tokens[tenant.lower()]
ret = jwt.decode(token, options={"verify_signature": False},algorithms=['RS256'])
curTime = round(time.time()) + 120
if ret[Constants.TOKEN_CLAIM_EXPIRY] > curTime :
self.logger.debug("Access Token valid. Returning from cache.")
return token
else:
self.logger.debug("AccessToken expired.")
self.logger.debug("Going to fetch new Access Token.")
am = AuthenticationManager(self.options)
if Constants.CLIENT_ID not in self.options:
raise ValueError("ClientId is missing in required options for fetching Access Token.")
if Constants.CLIENT_SECRET not in self.options:
raise ValueError("ClientSecret is missing in required options for fetching Access Token.")
res = am.clientCredentials(Constants.MY_SCOPES)
CacheManager.tokens[tenant.lower()] = res.getAccessToken()
self.logger.debug("Access Token fetched successfully. Persisting in cache and returning.")
return res.getAccessToken()
class UserAssert:
def __init__(self, options, cacheManager):
"""
Default Constructor
:param options: A Dictionary containing BaseUrl, ClientId, and ClientSecret
"""
self.options = options
self.logger = Utils.getLogger(options)
self.asserterCache = cacheManager.getAsserterCache()
def assertClaims(self, jwt):
"""
This method asserts the identity with App Roles and Group Memberships for a given token
:param token: Access Token or Id Token
:return: a JSON Object with asserted Attributes else throws IDCSException
"""
id = None
tenant = None
subType = None
claim_user_id = self.options[Constants.USER_ID_TOK_CLAIM] if Constants.USER_ID_TOK_CLAIM in self.options else Constants.TOKEN_CLAIM_USER_ID
if "AT" == jwt[Constants.TOKEN_CLAIM_TOKEN_TYPE] and claim_user_id not in jwt:
id = jwt[self.options[Constants.CLIENT_ID_TOK_CLAIM] if Constants.CLIENT_ID_TOK_CLAIM in self.options else Constants.TOKEN_CLAIM_CLIENT_ID]
tenant = jwt[self.options[Constants.CLIENT_TENANT_TOK_CLAIM] if Constants.CLIENT_TENANT_TOK_CLAIM in self.options else Constants.TOKEN_CLAIM_CLIENT_TENANT]
else:
id = jwt[claim_user_id]
tenant = jwt[self.options[Constants.USER_TENANT_TOKEN_CLAIM] if Constants.USER_TENANT_TOKEN_CLAIM in self.options else Constants.TOKEN_CLAIM_USER_TENANT]
if Constants.TOKEN_CLAIM_SUB_TYPE in jwt:
subType = jwt[Constants.TOKEN_CLAIM_SUB_TYPE]
if six.PY2:
id = id.encode("utf-8")
# if "AT" == jwt[Constants.TOKEN_CLAIM_TOKEN_TYPE] and not id.endswith("_APPID"):
# return jwt
if Constants.ONLY_USER_TOK_CLAIM_ENABLED in self.options and not self.options[Constants.ONLY_USER_TOK_CLAIM_ENABLED]:
group_claim = self.options[Constants.GROUP_TOKEN_CLAIM] if Constants.GROUP_TOKEN_CLAIM in self.options else Constants.TOKEN_CLAIM_GROUPS
appRole_claim = self.options[Constants.APP_ROLE_TOKEN_CLAIM] if Constants.APP_ROLE_TOKEN_CLAIM in self.options else Constants.TOKEN_CLAIM_APP_ROLES
if group_claim in jwt or appRole_claim in jwt:
return jwt
key = tenant + ":" + id
if self.asserterCache.contains(key):
self.logger.debug("Claims Found in Cache. Returning from cache")
claims = self.asserterCache.get(key)
jwt.update(claims)
return
mdm = MetadataManager(self.options, tenant)
md = mdm.getMetaData()
url = md.getAsserterUrl()
atm = AccessTokenManager(self.options)
at = atm.getAccessToken()
headers = {}
headers[Constants.HEADER_AUTHORIZATION] = Constants.AUTH_BEARER % at
headers[Constants.HEADER_CONTENT] = Constants.APPLICATION_JSON
body = {}
if Constants.APP_NAME in self.options:
body[Constants.IDCS_APPNAME_FILTER_ATTRIB] = self.options[Constants.APP_NAME]
if (id.endswith("_APPID") or (subType is not None and subType == "client")):
var = "do nothing here"
else:
body[Constants.IDCS_MAPPING_ATTRIBUTE] = self.options[Constants.USER_ID_RES_ATTR] if Constants.USER_ID_RES_ATTR in self.options else Constants.MAPPING_ATTR_ID
# if not id.endswith("_APPID"):
# body[Constants.IDCS_MAPPING_ATTRIBUTE] = self.options[Constants.USER_ID_RES_ATTR] if Constants.USER_ID_RES_ATTR in self.options else Constants.MAPPING_ATTR_ID
body[Constants.IDCS_MAPPING_ATTRIBUTE_VALUE] = id
schemas = [Constants.IDCS_ASSERTER_SCHEMA]
body[Constants.IDCS_SCHEMAS] = schemas
body[Constants.IDCS_INCLUDE_MEMBERSHIPS] = True
if (subType is not None and subType == "client"):
body[Constants.SUBJECT_TYPE_ATTR] = subType
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.post(url, json=body, headers=headers, verify=verify)
if response.status_code != 201 and response.status_code != 200:
self.logger.error("Unable to Assert Claims. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to Assert. Response text server %s", response.text)
raise IdcsException("Failed to Assert Claims", response)
res = response.json()
##CacheManager.asserterCache[key] = res
self.asserterCache.put(key,res)
jwt.update(res)
return jwt
class TokenVerifier:
"""
This class provide methods to verify access and id tokens
"""
def __init__(self, options, cacheManager = None):
"""
Default Constructor
:param options: A Dictionary containing BaseUrl, ClientId, and ClientSecret
"""
self.options = options
self.logger = Utils.getLogger(options)
if cacheManager is None:
cacheManager = CacheManager()
self.fqsCache = cacheManager.getFqsCache()
def verifyJwtToken(self, token):
"""
This method verifies a JWT token, its signature, and expiry
:param token: JWT Token
:return: decoded JWT token as a JSON Object
"""
try:
header = jwt.get_unverified_header(token)
decoded = jwt.decode(token, options={"verify_signature": False},algorithms=['RS256'])
except:
raise IdcsException("Failed to Decode JWT Token")
tenant = Utils.getTenantNameFromClaim(decoded, self.options)
kid = header[Constants.HEADER_CLAIM_KEY_ID]
km = KeyManager(self.options, tenant)
jwks = km.fetchKey()
for val in jwks[Constants.KEYS]:
if val.get(Constants.HEADER_CLAIM_KEY_ID) is not None and val[Constants.HEADER_CLAIM_KEY_ID] == kid:
jwk = val
break
else:
jwk = jwks[Constants.KEYS][0]
x5c = jwk[Constants.X5C][0]
try:
cert_obj = x509.load_der_x509_certificate(base64.b64decode(x5c), default_backend())
public_key = cert_obj.public_key()
options = {
'verify_signature': True,
'verify_exp': False,
'verify_nbf': False,
'verify_iat': False,
'verify_aud': False
}
level = self.options[Constants.TOKEN_VALIDATION_LEVEL] if Constants.TOKEN_VALIDATION_LEVEL in self.options else Constants.VALIDATION_LEVEL_FULL
verify = False if Constants.VALIDATION_LEVEL_NONE == level else True
ret = jwt.decode(token, public_key, options=options, verify=verify, algorithms=[jwk[Constants.ALG]], issuer=Utils.getTokenIssuerUrl(self.options))
skew = Constants.TOKEN_CLOCK_SKEW_DEFAULT_VALUE
if Constants.TOKEN_CLOCK_SKEW in self.options:
skew = self.options[Constants.TOKEN_CLOCK_SKEW]
if (ret[Constants.TOKEN_CLAIM_EXPIRY] + skew) <= round(time.time()):
self.logger.debug("JWT Token is expired.")
raise IdcsException("JWT Token is expired")
crossTenant = False
if Constants.CROSS_TENANT in self.options:
crossTenant = self.options[Constants.CROSS_TENANT]
if crossTenant:
res = re.search("idcs-[(a-z)|(0-9)]{32}$", tenant)
if res is None:
raise IdcsException("tenant present is token doesnot comply with idcs standards")
else:
if Utils.getTenant(self.options).lower() != tenant.lower():
raise IdcsException("tenant present is token doesn't match with already configured tenant")
return ret
except Exception as e:
self.logger.error(e)
error = "Failed to Verify Signature on JWT Token"
if(e.args is not None and e.args[0] is not None):
error += ": "+e.args[0]
raise IdcsException(error)
def validateAudience(self, token, isIdToken):
"""
Method to validate Audience
:param token: decoded JWT as a JSON Object
:param isIdToken: true if token id_token else false
:return: true is Audience is valid else false
"""
if Constants.TOKEN_CLAIM_AUDIENCE not in token:
if Constants.TOKEN_CLAIM_SCOPE not in token:
return False
else:
scope = token[Constants.TOKEN_CLAIM_SCOPE]
return Utils.isEmpty(scope)
else:
aud = token[Constants.TOKEN_CLAIM_AUDIENCE]
if not isinstance(aud, list):
aud = [aud]
necessary = self.getNecessaryAudience(aud)
if len(necessary) == 0:
return self.validateSufficientAudience(token, aud,isIdToken)
else:
return self.validateNecessaryAudience(token, necessary)
def getNecessaryAudience(self, aud):
necessary = []
for audience in aud:
if audience.startswith(Constants.NECESSARY_AUDIENCE_PREFIX):
necessary.append(audience)
return necessary
def validateSufficientAudience(self, token, aud, isIdToken):
if self.options[Constants.CROSS_TENANT] and isIdToken:
self.logger.info("validateSufficientAudience for idToken and cross tenant case returning true")
return True
resourceTenant = Utils.getTenantNameFromClaim(token, self.options)
for audience in aud:
if isIdToken:
if audience == self.options[Constants.CLIENT_ID]:
return True
else:
if self.__validateSufficientAudience(urlparse(audience), urlparse(self.options[Constants.AUDIENCE_SERVICE_URL]), resourceTenant):
return True
return False
def __validateSufficientAudience(self, audienceUrl, serviceUrl, resourceTenant):
if serviceUrl.scheme != audienceUrl.scheme:
return False
host = serviceUrl.hostname
crossTenant = False
if Constants.CROSS_TENANT in self.options:
crossTenant = self.options[Constants.CROSS_TENANT]
if crossTenant:
try:
idx = host.index(".")
host = resourceTenant + host[idx:]
except:
return False
if audienceUrl.hostname != host:
return False
#if audienceUrl.port is not None:
if audienceUrl.port is None:
if audienceUrl.scheme == "https":
audPortFromToken = 443
else:
audPortFromToken = 80
else:
audPortFromToken = audienceUrl.port
if serviceUrl.port is None:
if serviceUrl.scheme == "https":
audPortFromServiceUrl = 443
else:
audPortFromServiceUrl = 80
else:
audPortFromServiceUrl = serviceUrl.port
if audPortFromToken != audPortFromServiceUrl:
return False
if audienceUrl.path != "":
if not serviceUrl.path.startswith(audienceUrl.path):
return False
return True
def validateNecessaryAudience(self, token, necessary):
for audience in necessary:
if not self.__validateNecessaryAudience(token, audience):
return False
return True
def __validateNecessaryAudience(self, token, audience):
if Constants.AUDIENCE_SCOPE_ACCOUNT == audience:
return self.__validateScopeAccount(token)
elif audience.startswith(Constants.AUDIENCE_SCOPE_TAG):
return self.__validateScopeTag(audience)
else:
return False
def __validateScopeAccount(self, token):
client_tenant = token[Constants.TOKEN_CLAIM_TENANT]
tenant = Utils.getTenant(self.options)
if tenant == client_tenant:
return True
else:
return False
def __validateScopeTag(self, audience):
tokenTags = self.getTokenTags(audience)
scopes = Utils.getFqs(self.options)
for scope in scopes:
resTags = self.getTagsForResource(scope)
for key, value in resTags.items():
if key in tokenTags:
return True
return False
def getTokenTags(self, audience):
ret = {}
i = audience.index("=")
decoded = base64.b64decode(audience[i+1:])
parsed = json.loads(decoded)
if "tags" in parsed:
tags = parsed["tags"]
for tag in tags:
ret[tag["key"] + ":" + tag["value"]] = ""
return ret
def getTagsForResource(self, scope):
key = scope
if self.fqsCache.contains(key):
tags = self.fqsCache.get(key)
if tags.getExpiry() > round(time.time()):
return tags.getTags()
ret = {}
atm = AccessTokenManager(self.options)
at = atm.getAccessToken()
url = self.options[Constants.BASE_URL]
url += Constants.GET_APP_INFO_PATH
params = {}
params["filter"] = Constants.FQS_FILTER % scope
enc = urllib.parse.urlencode(params)
url += "?" + enc
headers = {}
headers[Constants.HEADER_AUTHORIZATION] = Constants.AUTH_BEARER % at
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.get(url, headers=headers, verify=verify)
if response.status_code != 200:
self.logger.error("Unable to fetch App Info. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch App Info. Response text server %s", response.text)
raise IdcsException("Failed to obtain App Details", response)
res = response.json()
resources = res["Resources"]
for resource in resources:
if "tags" in resource:
tags = resource["tags"]
for tag in tags:
ret[tag["key"] + ":" + tag["value"]] = ""
ttl = Constants.FQS_RESOURCE_CACHE_TTL_DEFAULT
if Constants.FQS_RESOURCE_CACHE_TTL in self.options:
ttl = self.options[Constants.FQS_RESOURCE_CACHE_TTL]
self.fqsCache.put(key,Tags(ret, ttl))
return ret
class KeyManager:
"""
This class provide methods to fetch and manage JWK for tenants
"""
def __init__(self, options, tenant = None):
"""
Default Constructor
:param options: A Dictionary containing BaseUrl, ClientId, and ClientSecret
"""
self.options = options
if tenant is not None:
self.tenant = tenant
else:
self.tenant = Utils.getTenant(self.options)
self.logger = Utils.getLogger(options)
def fetchKey(self):
"""
This method fetches JWK of the tenant for the BaseUrl given in options
:return: JSON Web Key of the tenant
"""
tenant = self.tenant
if tenant.lower() in CacheManager.keys:
self.logger.debug("Key found Cache.")
jwk = CacheManager.keys[tenant.lower()]
if jwk.getExpiry() > round(time.time()):
self.logger.debug("Returning from cache.")
return jwk.getJwk()
else:
self.logger.debug("JWK is expired.")
self.logger.debug("JWK Not present in cache or expired. Going to fetch from server.")
atm = AccessTokenManager(self.options)
token = atm.getAccessToken()
mdm = MetadataManager(self.options, tenant)
md = mdm.getMetaData()
url = md.getJwksUrl()
self.logger.debug("Going to fetch JWK from %s", url)
headers = {Constants.HEADER_AUTHORIZATION: Constants.AUTH_BEARER % token}
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.get(url, headers=headers, verify=verify)
if response.status_code == 200 :
res = response.json()
CacheManager.keys[tenant] = Jwk(res)
self.logger.debug("JWK fetched successfully. Persisting in cache and returning.")
return res
self.logger.error("Unable to fetch JWK. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch JWK. Response text server %s", response.text)
raise IdcsException("Failed to Fetch JWK", response)
class AuthenticationManager:
"""
This class provide methods for the different OAUTH authentication flows to get Access Token
"""
def __init__(self, options):
"""
Default Constructor
:param options: A Dictionary containing BaseUrl, ClientId, and ClientSecret
"""
self.options = Utils.validateOptions(options)
self.logger = Utils.getLogger(options)
self.cacheManager = CacheManager()
self.tokenCache = self.cacheManager.getTokenCache()
def verifyToken(self, token):
"""
This method verifies idToken or accessToken given and parse it and return decoded token
:param token: id_token or access_token
:return: decoded token as JSON Object
"""
if token is None or not token.strip():
raise ValueError("token is empty")
key = hash(token)
verifiedJwt = self.tokenCache.get(key)
if verifiedJwt is None:
self.logger.info("token claims not found in cache")
tv = TokenVerifier(self.options, self.cacheManager)
verifiedJwt = tv.verifyJwtToken(token)
if verifiedJwt is None :
return None
type = verifiedJwt[Constants.TOKEN_CLAIM_TOKEN_TYPE]
isIdToken = False if "AT" == type else True
level = self.options[Constants.TOKEN_VALIDATION_LEVEL] if Constants.TOKEN_VALIDATION_LEVEL in self.options else Constants.VALIDATION_LEVEL_FULL
if Constants.VALIDATION_LEVEL_FULL == level:
valid = tv.validateAudience(verifiedJwt, isIdToken)
if not valid:
raise IdcsException("Failed to Verify Audience")
ttl = Utils.getTTLFromClaim(verifiedJwt)
if key is not None and ttl > 0:
self.tokenCache.put(key, verifiedJwt, ttl)
if verifiedJwt is not None:
userAssert = UserAssert(self.options, self.cacheManager)
userAssert.assertClaims(verifiedJwt)
return verifiedJwt
def verifyIdToken(self, id_token):
"""
This method verifies idToken given and parse ite and return IdToken Object
:param id_token: idToken of User
:return: IdToken Class object containing claims present in idToken. Returns Null id fails to verify.
"""
token = self.verifyToken(id_token)
return IdToken(token)
def verifyAccessToken(self, access_token):
"""
This method verifies accessToken given and parse ite and return AccessToken Object
:param access_token: access Token
:return: Access Token Class object containing claims present in access token. Returns Null id fails to verify.
"""
token = self.verifyToken(access_token)
return AccessToken(token)
def getAuthorizationCodeUrl(self, redirect_uri, scope=None, state=None, response_type=None, nonce=None):
"""
This method returns the Authorization Code URL for the tenant for the BaseUrl present in options
:param redirect_uri: The redirect_uri where authorization code would be sent back
:param scope: The scopes for which the authorization code is returned
:param state: The state to be passed to OAUTH provider
:param response_type The response type required from OAUTH Provider
:param nonce The nonce is used for openId verification to prevent replay attacks. Use other method for non openid flow
:return: A complete formed URL at which the browser should hit to get the authorization code
"""
if redirect_uri is None or not redirect_uri.strip():
raise ValueError("redirect_uri is empty")
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
url = md.getAuthorizationUrl()
self.logger.debug("Got Authorization Endpoint %s", url)
params = {}
params[Constants.PARAM_CLIENT_ID] = self.options[Constants.CLIENT_ID]
if response_type is None:
params[Constants.PARAM_RESPONSE_TYPE] = Constants.RESPONSE_TYPE_CODE
else:
params[Constants.PARAM_RESPONSE_TYPE] = response_type
params[Constants.PARAM_REDIRECT_URI] = redirect_uri
if scope is not None:
params[Constants.PARAM_SCOPE] = scope
if state is not None:
params[Constants.PARAM_STATE] = state
if nonce is not None:
params[Constants.PARAM_NONCE] = nonce
url += "?" + urllib.parse.urlencode(params)
self.logger.debug("Returning Authorization code Url %s", url)
return url
def authorizationCode(self, code, nonce=None):
"""
This methods fetched access token for the authorization code flow
:param code: The authorization code sent by OAUTH provider
:param nonce The nonce is used for openId verification to prevent replay attacks. Use other method for non openid flow
:return: AuthenticationResult Object containing claims returned in Authentication
"""
if Constants.CLIENT_ID not in self.options:
raise ValueError("ClientId is missing in required options for fetching Access Token.")
if Constants.CLIENT_SECRET not in self.options:
raise ValueError("ClientSecret is missing in required options for fetching Access Token.")
if code is None or not code.strip():
raise ValueError("code is empty")
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
url = md.getTokenUrl()
self.logger.debug("Got Token Endpoint %s", url)
auth = self.options[Constants.CLIENT_ID] + ":" + self.options[Constants.CLIENT_SECRET]
encode = base64.b64encode(auth.encode(Constants.UTF8))
basicAuth = Constants.AUTH_BASIC % encode.decode(Constants.UTF8)
headers = {Constants.HEADER_CONTENT : Constants.WWW_FORM_ENCODED,
Constants.HEADER_AUTHORIZATION: basicAuth}
params = {Constants.PARAM_GRANT_TYPE : Constants.GRANT_AUTHZ_CODE, Constants.PARAM_CODE : code}
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.post(url, data=params, headers=headers, verify=verify)
if response.status_code == 200 :
res = response.json()
self.logger.debug("Access Token fetched successfully from authorization code.")
try:
if Constants.ID_TOKEN in res:
#decoded = jwt.decode(res[Constants.ID_TOKEN], verify=False)
decoded = jwt.decode(res[Constants.ID_TOKEN],options={"verify_signature": False},algorithms=['RS256'] )
if(Constants.PARAM_NONCE in decoded):
if nonce is None or nonce == "":
err = "authorizationCode : Nonce should not be null."
self.logger.error(err)
raise IdcsException(err)
if nonce != decoded[Constants.PARAM_NONCE]:
err = "authorizationCode : Nonce didn't match."
self.logger.error(err)
raise IdcsException(err)
except:
raise IdcsException("Failed to Decode JWT Token")
return AuthenticationResult(res)
self.logger.error("Unable to fetch Access Token. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch Access Token. Response text server %s", response.text)
raise IdcsException("Failed to obtain access token", response)
def resourceOwner(self, username, password, scope=None):
"""
This method fetches Access Token using resource owner OAUTH flow
:param username: Login Id used to do login
:param password: Password of the User
:param scope: List of scopes for which access token is required
:return: AuthenticationResult Object containing claims returned in Authentication
"""
if Constants.CLIENT_ID not in self.options:
raise ValueError("ClientId is missing in required options for fetching Access Token.")
if Constants.CLIENT_SECRET not in self.options:
raise ValueError("ClientSecret is missing in required options for fetching Access Token.")
if username is None or not username.strip():
raise ValueError("username is empty")
if password is None or not password.strip():
raise ValueError("password is empty")
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
url = md.getTokenUrl()
self.logger.debug("Got Token Endpoint %s", url)
auth = self.options[Constants.CLIENT_ID] + ":" + self.options[Constants.CLIENT_SECRET]
encode = base64.b64encode(auth.encode(Constants.UTF8))
basicAuth = Constants.AUTH_BASIC % encode.decode(Constants.UTF8)
headers = {Constants.HEADER_CONTENT : Constants.WWW_FORM_ENCODED,
Constants.HEADER_AUTHORIZATION: basicAuth}
params = {Constants.PARAM_GRANT_TYPE : Constants.GRANT_PASSWORD, Constants.PARAM_USER_NAME : username, Constants.PARAM_PASSWORD : password}
if scope is not None:
params[Constants.PARAM_SCOPE] = scope
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.post(url, data=params, headers=headers, verify=verify)
if response.status_code == 200 :
res = response.json()
self.logger.debug("Access Token fetched successfully using resource owner credentials")
return AuthenticationResult(res)
self.logger.error("Unable to fetch Access Token. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch Access Token. Response text server %s", response.text)
raise IdcsException("Failed to obtain access token", response)
def refreshToken(self, refresh_token, scope=None):
"""
This method fetches access token using the refresh token OAUTH flow
:param refresh_token: The refresh token to fetch access token
:param scope: List of scopes for which access token is required
:return: AuthenticationResult Object containing claims returned in Authentication
"""
if Constants.CLIENT_ID not in self.options:
raise ValueError("ClientId is missing in required options for fetching Access Token.")
if Constants.CLIENT_SECRET not in self.options:
raise ValueError("ClientSecret is missing in required options for fetching Access Token.")
if refresh_token is None or not refresh_token.strip():
raise ValueError("refresh_token is empty")
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
url = md.getTokenUrl()
self.logger.debug("Got Token Endpoint %s", url)
auth = self.options[Constants.CLIENT_ID] + ":" + self.options[Constants.CLIENT_SECRET]
encode = base64.b64encode(auth.encode(Constants.UTF8))
basicAuth = Constants.AUTH_BASIC % encode.decode(Constants.UTF8)
headers = {Constants.HEADER_CONTENT : Constants.WWW_FORM_ENCODED,
Constants.HEADER_AUTHORIZATION: basicAuth}
params = {Constants.PARAM_GRANT_TYPE : Constants.GRANT_REFRESH_TOKEN, Constants.PARAM_REFRESH_TOKEN : refresh_token}
if scope is not None:
params[Constants.PARAM_SCOPE] = scope
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.post(url, data=params, headers=headers, verify=verify)
if response.status_code == 200 :
res = response.json()
self.logger.debug("Access Token fetched successfully using refresh token")
return AuthenticationResult(res)
self.logger.error("Unable to fetch Access Token. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch Access Token. Response text server %s", response.text)
raise IdcsException("Failed to obtain access token", response)
def clientAssertion(self, user_assertion, client_assertion, scope=None):
"""
This method fetches access token using the Client Assertion OAUTH flow
:param user_assertion: User Assertion as JSON WEB Token
:param client_assertion: Client Assertion as JSON WEB Token
:param scope: List of scopes for which access token is required
:return: AuthenticationResult Object containing claims returned in Authentication
"""
if Constants.CLIENT_ID not in self.options:
raise ValueError("ClientId is missing in required options for fetching Access Token.")
if user_assertion is None or not user_assertion.strip():
raise ValueError("user_assertion is empty")
if client_assertion is None or not client_assertion.strip():
raise ValueError("client_assertion is empty")
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
url = md.getTokenUrl()
self.logger.debug("Got Token Endpoint %s", url)
headers = {Constants.HEADER_CONTENT : Constants.WWW_FORM_ENCODED}
params = {Constants.PARAM_GRANT_TYPE : Constants.GRANT_ASSERTION,
Constants.PARAM_CLIENT_ID : self.options[Constants.CLIENT_ID],
Constants.PARAM_ASSERTION : user_assertion,
Constants.PARAM_CLIENT_ASSERTION : client_assertion,
Constants.PARAM_CLIENT_ASSERTION_TYPE : Constants.ASSERTION_JWT}
if scope is not None:
params[Constants.PARAM_SCOPE] = scope
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.post(url, data=params, headers=headers, verify=verify)
if response.status_code == 200 :
res = response.json()
self.logger.debug("Access Token fetched successfully using client assertion")
return AuthenticationResult(res)
self.logger.error("Unable to fetch Access Token. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch Access Token. Response text server %s", response.text)
raise IdcsException("Failed to obtain access token", response)
def userAssertion(self, user_assertion, scope=None):
"""
This method fetches access token using the User Assertion OAUTH flow
:param user_assertion: User Assertion as JSON WEB Token
:param scope: List of scopes for which access token is required
:return: AuthenticationResult Object containing claims returned in Authentication
"""
if Constants.CLIENT_ID not in self.options:
raise ValueError("ClientId is missing in required options for fetching Access Token.")
if Constants.CLIENT_SECRET not in self.options:
raise ValueError("ClientSecret is missing in required options for fetching Access Token.")
if user_assertion is None or not user_assertion.strip():
raise ValueError("user_assertion is empty")
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
url = md.getTokenUrl()
self.logger.debug("Got Token Endpoint %s", url)
auth = self.options[Constants.CLIENT_ID] + ":" + self.options[Constants.CLIENT_SECRET]
encode = base64.b64encode(auth.encode(Constants.UTF8))
basicAuth = Constants.AUTH_BASIC % encode.decode(Constants.UTF8)
headers = {Constants.HEADER_CONTENT : Constants.WWW_FORM_ENCODED,
Constants.HEADER_AUTHORIZATION: basicAuth}
params = {Constants.PARAM_GRANT_TYPE : Constants.GRANT_ASSERTION,
Constants.PARAM_ASSERTION : user_assertion}
if scope is not None:
params[Constants.PARAM_SCOPE] = scope
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.post(url, data=params, headers=headers, verify=verify)
if response.status_code == 200 :
res = response.json()
self.logger.debug("Access Token fetched successfully using user assertion")
return AuthenticationResult(res)
self.logger.error("Unable to fetch Access Token. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch Access Token. Response text server %s", response.text)
raise IdcsException("Failed to obtain access token", response)
def clientCredentials(self, scope):
"""
This method fetches Access Token using the Client Credentials OAUTH Flow
:param scope: List of scopes for which access token is required
:return: AuthenticationResult Object containing claims returned in Authentication
"""
if Constants.CLIENT_ID not in self.options:
raise ValueError("ClientId is missing in required options for fetching Access Token.")
if Constants.CLIENT_SECRET not in self.options:
raise ValueError("ClientSecret is missing in required options for fetching Access Token.")
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
url = md.getTokenUrl()
auth = self.options[Constants.CLIENT_ID] + ":" + self.options[Constants.CLIENT_SECRET]
encode = base64.b64encode(auth.encode(Constants.UTF8))
basicAuth = Constants.AUTH_BASIC % encode.decode(Constants.UTF8)
headers = {Constants.HEADER_CONTENT : Constants.WWW_FORM_ENCODED,
Constants.HEADER_AUTHORIZATION: basicAuth}
params = {Constants.PARAM_GRANT_TYPE: Constants.GRANT_CLIENT_CRED,
Constants.PARAM_SCOPE: scope}
response = None
verify = True
if Constants.IGNORE_SSL in self.options:
verify = not bool(self.options[Constants.IGNORE_SSL])
response = requests.post(url, data=params, headers=headers, verify=verify)
if response.status_code == 200 :
res = response.json()
self.logger.debug("Access Token fetched successfully using client credentials")
return AuthenticationResult(res)
self.logger.error("Unable to fetch Access Token. Response Code from server %s", str(response.status_code))
self.logger.error("Unable to fetch Access Token. Response text server %s", response.text)
raise IdcsException("Failed to obtain access token", response)
def generateAssertion(self, privateKey, headers, claims, alg=None):
"""
This method produces a signed JWT from the given claims
:param privateKey: RSA Private Key to sign the assertion
:param headers: A dictionary of headers for Signed token. Claims kid or x5t are mandatory
:param claims: A dictionary of claims for Signed token. Claims sub,exp,aud are mandatory
:param alg: The algorithm used to sign. Default is RS256
:return: Serialized Signed Json Web Token
"""
if claims is None:
raise ValueError("Claims is empty")
if Constants.TOKEN_CLAIM_SUBJECT not in claims:
raise ValueError("Subject claim not present")
if Constants.TOKEN_CLAIM_EXPIRY not in claims:
raise ValueError("Expiry claim not present")
if Constants.TOKEN_CLAIM_AUDIENCE not in claims:
raise ValueError("Audience claim not present")
if Constants.TOKEN_CLAIM_ISSUE_AT not in claims:
raise ValueError("Issue At claim not present")
if Constants.TOKEN_CLAIM_ISSUER not in claims:
raise ValueError("Issuer claim not present")
if headers is None:
raise ValueError("Headers is empty")
if Constants.HEADER_CLAIM_KEY_ID not in headers:
if Constants.HEADER_CLAIM_X5_THUMB not in headers:
raise ValueError("No kid or x5t present in header")
if alg is None:
alg = "RS256"
headers[Constants.HEADER_CLAIM_TYPE] = Constants.TOKEN_TYPE_JWT
token = jwt.encode(claims, privateKey, headers=headers, algorithm=alg)
return token.decode("utf-8")
"""
def getLogoutUrl(self, postLogoutRedirectUri, idTokenHint, state=None):
if idTokenHint is None or not idTokenHint.strip():
raise ValueError("token is empty")
key = hash(idTokenHint)
self.cacheManager.getTokenCache().remove(key)
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
params = {}
if postLogoutRedirectUri is not None:
params[Constants.PARAM_POST_LOGOUT_URI] = postLogoutRedirectUri
if state is not None:
params[Constants.PARAM_STATE] = state
params[Constants.PARAM_ID_TOKEN_HINT] = idTokenHint
logoutUrl = md.metadata[Constants.META_OPENID_CONFIGURATION][Constants.META_OPENID_CONFIGURATION_ENDSESSION_ENDPOINT]
self.logger.debug("Got logoutUrl %s", logoutUrl)
logoutUrl += "?" + urllib.parse.urlencode(params)
self.logger.debug("Returning logoutUrl %s", logoutUrl)
return logoutUrl
"""
def getLogoutUrl(self, postLogoutRedirectUri=None, idTokenHint=None, state=None):
"""
This method returns Logout URL for the tenant and clear the Token Cache
:param postLogoutRedirectUri: The postLogoutRedirectUri where post logout would be sent back
:param idTokenHint: The token used to inititate logout
:param state: The state to be passed to OAUTH provider
:return: A complete formed URL at which the browser should hit to logout else returns error
"""
mdm = MetadataManager(self.options)
md = mdm.getMetaData()
params = {}
if idTokenHint is not None:
key = hash(idTokenHint)
self.cacheManager.getTokenCache().remove(key)
params[Constants.PARAM_ID_TOKEN_HINT] = idTokenHint
if postLogoutRedirectUri is not None:
params[Constants.PARAM_POST_LOGOUT_URI] = postLogoutRedirectUri
if state is not None:
params[Constants.PARAM_STATE] = state
logoutUrl = md.metadata[Constants.META_OPENID_CONFIGURATION][
Constants.META_OPENID_CONFIGURATION_ENDSESSION_ENDPOINT]
self.logger.debug("Got logoutUrl %s", logoutUrl)
logoutUrl += "?" + urllib.parse.urlencode(params)
self.logger.debug("Returning logoutUrl %s", logoutUrl)
return logoutUrl
@deprecated
class UserManager:
"""
This Class provides methods to fetch User Details
"""
def __init__(self, options):
"""
Default Constructor
:param options: A Dictionary containing BaseUrl, ClientId, and ClientSecret
"""
self.options = Utils.validateOptions(options)
self.logger = Utils.getLogger(options)
self.userCache = CacheManager().getUserCache()
self.asserterCache = CacheManager().getAsserterCache()
@deprecated