14
14
15
15
from typing import Dict
16
16
17
-
17
+ import warnings
18
18
from requests import PreparedRequest
19
19
from requests .auth import AuthBase
20
20
21
+ from ibm_cloud_sdk_core import IAMTokenManager
22
+ from ..utils .utils import cname_from_crn
23
+
24
+ CLOUD_IAM_URL = "iam.cloud.ibm.com"
25
+ STAGING_CLOUD_IAM_URL = "iam.test.cloud.ibm.com"
26
+
21
27
22
28
class CloudAuth (AuthBase ):
23
29
"""Attaches IBM Cloud Authentication to the given Request object."""
24
30
25
- def __init__ (self , api_key : str , crn : str ):
26
- self .api_key = api_key
31
+ def __init__ (self , api_key : str , crn : str , private : bool = False ):
27
32
self .crn = crn
33
+ self .api_key = api_key
34
+ iam_url = (
35
+ f"https://{ 'private.' if private else '' } "
36
+ f"{ STAGING_CLOUD_IAM_URL if cname_from_crn (crn ) == 'staging' else CLOUD_IAM_URL } "
37
+ )
38
+ self .tm = IAMTokenManager (api_key , url = iam_url )
28
39
29
40
def __eq__ (self , other : object ) -> bool :
30
41
if isinstance (other , CloudAuth ):
@@ -42,7 +53,14 @@ def __call__(self, r: PreparedRequest) -> PreparedRequest:
42
53
43
54
def get_headers (self ) -> Dict :
44
55
"""Return authorization information to be stored in header."""
45
- return {"Service-CRN" : self .crn , "Authorization" : f"apikey { self .api_key } " }
56
+ try :
57
+ access_token = self .tm .get_token ()
58
+ return {"Service-CRN" : self .crn , "Authorization" : f"Bearer { access_token } " }
59
+ except Exception as ex : # pylint: disable=broad-except
60
+ warnings .warn (
61
+ f"Unable to retrieve IBM Cloud access token. API Key will be used instead. { ex } "
62
+ )
63
+ return {"Service-CRN" : self .crn , "Authorization" : f"apikey { self .api_key } " }
46
64
47
65
48
66
class QuantumAuth (AuthBase ):
0 commit comments