def device_flow_session(client_id, auto=False): ctx = AuthenticationContext(AUTHORITY_URL, api_version=None) device_code = ctx.acquire_user_code(RESOURCE, client_id) if auto: pyperclip.copy(device_code['user_code']) webbrowser.open(device_code['verification_url']) print( f'The code {device_code["user_code"]} has been copied to your clipboard, ' f'and your web browser is opening {device_code["verification_url"]}. ' 'Paste the code to sign in.') else: print(device_code['message']) token_response = ctx.acquire_token_with_device_code( RESOURCE, device_code, client_id) if not token_response.get('accessToken', None): return None session = requests.Session() session.headers.update({ 'Authorization': f'Bearer {token_response["accessToken"]}', 'SdkVersion': 'sample-python-adal', 'x-client-SKU': 'sample-python-adal' }) return session
def _get_token(self): context = AuthenticationContext(self.authority_uri) code = context.acquire_user_code(self.client_uri, self.client_id) _prompt_for_code(code) self.config_data = context.acquire_token_with_device_code( self.client_uri, code, self.client_id) self._cache_creds()
def acquire_token_with_device_code(client_id, auto=False): """Obtain an access token from Azure AD (via device flow) and create a Requests session instance ready to make authenticated calls to Microsoft Graph. client_id = Application ID for registered "Azure AD only" V1-endpoint app auto = whether to copy device code to clipboard and auto-launch browser Returns Requests session object if user signed in successfully. The session includes the access token in an Authorization header. User identity must be an organizational account (ADAL does not support MSAs). """ ctx = AuthenticationContext(AUTHORITY_URL, api_version=None) device_code = ctx.acquire_user_code(RESOURCE, client_id) # display user instructions if auto: pyperclip.copy(device_code['user_code']) # copy user code to clipboard webbrowser.open(device_code['verification_url']) # open browser print(f'The code {device_code["user_code"]} has been copied to your clipboard, ' f'and your web browser is opening {device_code["verification_url"]}. ' 'Paste the code to sign in.') else: print(device_code['message']) return ctx.acquire_token_with_device_code(RESOURCE, device_code, client_id)
def get_client(cluster): """ get cached, authenticated client for given cluster """ assert isinstance(cluster, str) assert cluster.startswith('https') global _client_cache c = _client_cache.get(cluster) if c is None: # create new auth context ac = AuthenticationContext("https://login.microsoftonline.com/common") client_id = NotebookKustoClient.client_id() # create parameters user_code_info = ac.acquire_user_code(cluster, client_id) # ask user to authenticate somehow code = user_code_info[OAuth2DeviceCodeResponseParameters.USER_CODE] url = user_code_info[ OAuth2DeviceCodeResponseParameters.VERIFICATION_URL] promp_for_aad_device_login(url=url, text='Authenticate', code=code) # wait for user to input code token = ac.acquire_token_with_device_code(cluster, user_code_info, client_id) assert token is not None _client_cache[cluster] = c = NotebookKustoClient(cluster, ac) return c
def device_flow_session(client_id, auto=True): ctx = AuthenticationContext(config.AUTHORITY_URL, api_version=None) device_code = ctx.acquire_user_code(config.RESOURCE, client_id) # display user instructions if auto: print( f'Le code {device_code["user_code"]} a ete copie dans le presse-papier ' f' et votre navigateur est en train d´ouvrir la page {device_code["verification_url"]}. ' 'Coller le code pour se connecter.') pyperclip.copy(device_code['user_code']) # copy user code to clipboard webbrowser.open(device_code['verification_url']) # open browser else: print(device_code['message']) token_response = ctx.acquire_token_with_device_code( config.RESOURCE, device_code, client_id) if not token_response.get('accessToken', None): return None session = requests.Session() session.headers.update( {'Authorization': f'Bearer {token_response["accessToken"]}'}) return session
class _AadHelper(object): def __init__( self, kusto_cluster, client_id=None, client_secret=None, username=None, password=None, authority=None, ): self.adal_context = AuthenticationContext( "https://login.windows.net/{0}".format(authority or "microsoft.com")) self.kusto_cluster = kusto_cluster self.client_id = client_id or "db662dc1-0cfe-4e1c-a843-19a68e65be58" self.client_secret = client_secret self.username = username self.password = password def acquire_token(self): """A method to acquire tokens from AAD.""" token_response = self.adal_context.acquire_token( self.kusto_cluster, self.username, self.client_id) if token_response is not None: expiration_date = dateutil.parser.parse( token_response["expiresOn"]) if expiration_date > datetime.utcnow() + timedelta(minutes=5): return token_response["accessToken"] if self.client_secret is not None and self.client_id is not None: token_response = self.adal_context.acquire_token_with_client_credentials( self.kusto_cluster, self.client_id, self.client_secret) elif self.username is not None and self.password is not None: token_response = self.adal_context.acquire_token_with_username_password( self.kusto_cluster, self.username, self.password, self.client_id) else: code = self.adal_context.acquire_user_code(self.kusto_cluster, self.client_id) print(code["message"]) webbrowser.open(code["verification_url"]) token_response = self.adal_context.acquire_token_with_device_code( self.kusto_cluster, code, self.client_id) return token_response["accessToken"]
def login(self, tenant): auth_context = AuthenticationContext( AzureTokenService.authority_url_format.format(tenant)) user_code = auth_context.acquire_user_code( AzureTokenService.resource_url, AzureTokenService.client_id) self.__write_line(user_code['message']) self.__token = auth_context.acquire_token_with_device_code( AzureTokenService.resource_url, user_code, AzureTokenService.client_id) self.__tenant = tenant self.__tenant_id = self.__token["tenantId"] self.__logged_in_user = self.__token["userId"] self.__credentials = AADTokenCredentials(self.__token, AzureTokenService.client_id) self.__update_refresh_token_timer()
def device_flow_session(client_id, auto=False): ctx = AuthenticationContext(AUTHORITY_URL, api_version=None) device_code = ctx.acquire_user_code(RESOURCE, client_id) if path.exists(TOKEN_PATH): with open(TOKEN_PATH, 'r') as f: token_info = json.load(f) if not expired(token_info['expiresOn']): print("You're already logged in") token = token_info['accessToken'] else: print("Expired token") token = first_time(ctx, device_code) else: token = first_time(ctx, device_code) session = requests.Session() session.headers.update({ 'Authorization': f'Bearer {token}', 'SdkVersion': 'sample-python-adal', 'x-client-SKU': 'sample-python-adal' }) return session
def get_session(): """ Gets a valid Microsoft Graph HTTP-Session. Will ask the user for permission. """ # Create new authentication context which will be # used to have access to the user's information. auth_context = AuthenticationContext(config.AUTHORITY_URL, api_version=None) # Get the device code. device_code = auth_context.acquire_user_code(config.RESOURCE, config.CLIENT_ID) # Print user call to action message. # This will lead the user to an Microsoft Login page. print(' {}'.format(device_code['message'])) # Send the Wait for the process to complete. response = auth_context.acquire_token_with_device_code( config.RESOURCE, device_code, config.CLIENT_ID) # Check if all required attributes exists. if not response.get('accessToken', None): return None # Create and pre-configure session. session = requests.Session() token = response["accessToken"] session.headers.update({ 'Authorization': 'Bearer {}'.format(token), 'SdkVersion': '{}'.format(config.APP_NAME), 'x-client-SKU': '{}'.format(config.APP_NAME), 'Accept': 'application/json', 'Content-Type': 'application/json' }) # Return session instance. return session
class _MyAadHelper(object): def __init__(self, kcsb, default_clientid): authority = kcsb.authority_id or "common" self._resource = "{0.scheme}://{0.hostname}".format( urlparse(kcsb.data_source)) self._adal_context = AuthenticationContext( "https://login.microsoftonline.com/{0}".format(authority)) self._username = None if all([kcsb.aad_user_id, kcsb.password]): self._authentication_method = AuthenticationMethod.aad_username_password self._client_id = default_clientid self._username = kcsb.aad_user_id self._password = kcsb.password elif all([kcsb.application_client_id, kcsb.application_key]): self._authentication_method = AuthenticationMethod.aad_application_key self._client_id = kcsb.application_client_id self._client_secret = kcsb.application_key elif all([ kcsb.application_client_id, kcsb.application_certificate, kcsb.application_certificate_thumbprint ]): self._authentication_method = AuthenticationMethod.aad_application_certificate self._client_id = kcsb.application_client_id self._certificate = kcsb.application_certificate self._thumbprint = kcsb.application_certificate_thumbprint else: self._authentication_method = AuthenticationMethod.aad_device_login self._client_id = default_clientid def acquire_token(self, **options): """Acquire tokens from AAD.""" token = self._adal_context.acquire_token(self._resource, self._username, self._client_id) if token is not None: expiration_date = dateutil.parser.parse( token[TokenResponseFields.EXPIRES_ON]) if expiration_date > datetime.now() + timedelta(minutes=1): return self._get_header(token) if TokenResponseFields.REFRESH_TOKEN in token: token = self._adal_context.acquire_token_with_refresh_token( token[TokenResponseFields.REFRESH_TOKEN], self._client_id, self._resource) if token is not None: return self._get_header(token) if self._authentication_method is AuthenticationMethod.aad_username_password: token = self._adal_context.acquire_token_with_username_password( self._resource, self._username, self._password, self._client_id) elif self._authentication_method is AuthenticationMethod.aad_application_key: token = self._adal_context.acquire_token_with_client_credentials( self._resource, self._client_id, self._client_secret) elif self._authentication_method is AuthenticationMethod.aad_device_login: # print(code[OAuth2DeviceCodeResponseParameters.MESSAGE]) # webbrowser.open(code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL]) # token = self._adal_context.acquire_token_with_device_code( # self._resource, code, self._client_id # ) code: dict = self._adal_context.acquire_user_code( self._resource, self._client_id) url = code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL] device_code = code[ OAuth2DeviceCodeResponseParameters.USER_CODE].strip() html_str = ("""<!DOCTYPE html> <html><body> <!-- h1 id="user_code_p"><b>""" + device_code + """</b><br></h1--> <input id="kql_MagicCodeAuthInput" type="text" readonly style="font-weight: bold; border: none;" size = '""" + str(len(device_code)) + """' value='""" + device_code + """'> <button id='kql_MagicCodeAuth_button', onclick="this.style.visibility='hidden';kql_MagicCodeAuthFunction()">Copy code to clipboard and authenticate</button> <script> var kql_MagicUserCodeAuthWindow = null function kql_MagicCodeAuthFunction() { /* Get the text field */ var copyText = document.getElementById("kql_MagicCodeAuthInput"); /* Select the text field */ copyText.select(); /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ // alert("Copied the text: " + copyText.value); var w = screen.width / 2; var h = screen.height / 2; params = 'width='+w+',height='+h kql_MagicUserCodeAuthWindow = window.open('""" + url + """', 'kql_MagicUserCodeAuthWindow', params); // TODO: save selected cell index, so that the clear will be done on the lince cell } </script> </body></html>""") if options.get("notebook_app") in ["visualstudiocode", "ipython"]: Display.show_window('verification_url', url, **options) # Display.showInfoMessage("Code: {0}".format(device_code)) Display.showInfoMessage( "Copy code: {0} to verification url: {1} and authenticate". format(device_code, url), **options) else: Display.show_html(html_str) try: token = self._adal_context.acquire_token_with_device_code( self._resource, code, self._client_id) finally: html_str = """<!DOCTYPE html> <html><body><script> // close authentication window if (kql_MagicUserCodeAuthWindow && kql_MagicUserCodeAuthWindow.opener != null && !kql_MagicUserCodeAuthWindow.closed) { kql_MagicUserCodeAuthWindow.close() } // TODO: make sure, you clear the right cell. BTW, not sure it is a must to do any clearing // clear output cell Jupyter.notebook.clear_output(Jupyter.notebook.get_selected_index()) // TODO: if in run all mode, move to last cell, otherwise move to next cell // move to next cell </script></body></html>""" Display.show_html(html_str) elif self._authentication_method is AuthenticationMethod.aad_application_certificate: token = self._adal_context.acquire_token_with_client_certificate( self._resource, self._client_id, self._certificate, self._thumbprint) else: raise AuthenticationError("Unknown authentication method.") return self._get_header(token) def _get_header(self, token): return "{0} {1}".format(token[TokenResponseFields.TOKEN_TYPE], token[TokenResponseFields.ACCESS_TOKEN])
def authenticate_with_device_code(account_name): """Setup storage tokens by authenticating with device code and use management APIs Args: account_name (str): The storage account name for which to authenticate """ import urllib import json import os from tensorflow.python.platform import tf_logging as log try: from adal import AuthenticationContext except ModuleNotFoundError: log.error('Please install adal library with `python -m pip install -U adal`' 'to use the device code authentication method') return ctx = AuthenticationContext('https://login.microsoftonline.com/common') storage_resource = 'https://management.azure.com/' # Current multi-tenant client registerd in my AzureAD tenant client_id = '8c375311-7f4c-406c-84f8-03dfe11ba2d3' device_code = ctx.acquire_user_code( resource=storage_resource, client_id=client_id) # Display authentication message to user to action in their browser log.warn(device_code['message']) token_response = ctx.acquire_token_with_device_code( resource=storage_resource, user_code_info=device_code, client_id=client_id) headers = { 'Authorization': 'Bearer ' + token_response['accessToken'] } subscription_list_req = urllib.request.Request( url='https://management.azure.com/subscriptions?api-version=2016-06-01', headers=headers) with urllib.request.urlopen(subscription_list_req) as f: subscriptions = json.load(f) subscriptions = subscriptions['value'] storage_account = None for subscription in subscriptions: url = 'https://management.azure.com/subscriptions/{}/providers/Microsoft.Storage/storageAccounts?api-version=2019-04-01'.format(subscription['subscriptionId']) storage_account_list_req = urllib.request.Request( url=url, headers=headers) with urllib.request.urlopen(storage_account_list_req) as f: storage_accounts = json.load(f) storage_accounts = storage_accounts['value'] account_by_name = [s for s in storage_accounts if s.get('name') == account_name] if any(account_by_name): storage_account = account_by_name[0] break if storage_account is None: log.error("Couldn't find storage account {} in any " "available subscription".format(account_name)) return url = 'https://management.azure.com/{}/listKeys?api-version=2019-04-01'.format(storage_account['id']) storage_list_keys_req = urllib.request.Request( url=url, headers=headers, method='POST') with urllib.request.urlopen(storage_list_keys_req) as f: account_keys = json.load(f) os.environ['TF_AZURE_STORAGE_KEY'] = account_keys['keys'][0]['value'] log.info('Successfully set account key environment for {} ' 'storage account'.format(account_name))
class _AadHelper(object): def __init__(self, kcsb): authority = kcsb.authority_id or "microsoft.com" self._kusto_cluster = "{0.scheme}://{0.hostname}".format( urlparse(kcsb.data_source)) self._adal_context = AuthenticationContext("https://{0}/{1}".format( AADConstants.WORLD_WIDE_AUTHORITY, authority)) self._username = None if all([kcsb.aad_user_id, kcsb.password]): self._authentication_method = AuthenticationMethod.aad_username_password self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58" self._username = kcsb.aad_user_id self._password = kcsb.password elif all([kcsb.application_client_id, kcsb.application_key]): self._authentication_method = AuthenticationMethod.aad_application_key self._client_id = kcsb.application_client_id self._client_secret = kcsb.application_key elif all([ kcsb.application_client_id, kcsb.application_certificate, kcsb.application_certificate_thumbprint, ]): self._authentication_method = AuthenticationMethod.aad_application_certificate self._client_id = kcsb.application_client_id self._certificate = kcsb.application_certificate self._thumbprint = kcsb.application_certificate_thumbprint else: self._authentication_method = AuthenticationMethod.aad_device_login self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58" def acquire_token(self): """Acquire tokens from AAD.""" token = self._adal_context.acquire_token(self._kusto_cluster, self._username, self._client_id) if token is not None: expiration_date = dateutil.parser.parse( token[TokenResponseFields.EXPIRES_ON]) if expiration_date > datetime.now() + timedelta(minutes=1): return _get_header(token) if TokenResponseFields.REFRESH_TOKEN in token: token = self._adal_context.acquire_token_with_refresh_token( token[TokenResponseFields.REFRESH_TOKEN], self._client_id, self._kusto_cluster) if token is not None: return _get_header(token) if self._authentication_method is AuthenticationMethod.aad_username_password: token = self._adal_context.acquire_token_with_username_password( self._kusto_cluster, self._username, self._password, self._client_id) elif self._authentication_method is AuthenticationMethod.aad_application_key: token = self._adal_context.acquire_token_with_client_credentials( self._kusto_cluster, self._client_id, self._client_secret) elif self._authentication_method is AuthenticationMethod.aad_device_login: code = self._adal_context.acquire_user_code( self._kusto_cluster, self._client_id) print(code[OAuth2DeviceCodeResponseParameters.MESSAGE]) webbrowser.open( code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL]) token = self._adal_context.acquire_token_with_device_code( self._kusto_cluster, code, self._client_id) elif self._authentication_method is AuthenticationMethod.aad_application_certificate: token = self._adal_context.acquire_token_with_client_certificate( self._kusto_cluster, self._client_id, self._certificate, self._thumbprint) else: raise KustoClientError( "Please choose authentication method from azure.kusto.data.security.AuthenticationMethod" ) return _get_header(token)
class _AadHelper: authentication_method = None auth_context = None username = None kusto_uri = None authority_uri = None client_id = None password = None thumbprint = None certificate = None msi_params = None token_provider = None def __init__(self, kcsb): self.kusto_uri = "{0.scheme}://{0.hostname}".format( urlparse(kcsb.data_source)) self.username = None if all([kcsb.aad_user_id, kcsb.password]): self.authentication_method = AuthenticationMethod.aad_username_password self.client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58" self.username = kcsb.aad_user_id self.password = kcsb.password elif all([kcsb.application_client_id, kcsb.application_key]): self.authentication_method = AuthenticationMethod.aad_application_key self.client_id = kcsb.application_client_id self.client_secret = kcsb.application_key elif all([ kcsb.application_client_id, kcsb.application_certificate, kcsb.application_certificate_thumbprint ]): self.authentication_method = AuthenticationMethod.aad_application_certificate self.client_id = kcsb.application_client_id self.certificate = kcsb.application_certificate self.thumbprint = kcsb.application_certificate_thumbprint elif kcsb.msi_authentication: self.authentication_method = AuthenticationMethod.aad_msi self.msi_params = kcsb.msi_parameters return elif any([kcsb.user_token, kcsb.application_token]): self.token = kcsb.user_token or kcsb.application_token self.authentication_method = AuthenticationMethod.aad_token return elif kcsb.az_cli: self.authentication_method = AuthenticationMethod.az_cli_profile return elif kcsb.token_provider: self.authentication_method = AuthenticationMethod.token_provider self.token_provider = kcsb.token_provider else: self.authentication_method = AuthenticationMethod.aad_device_login self.client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58" authority = kcsb.authority_id or "common" aad_authority_uri = os.environ.get("AadAuthorityUri", CLOUD_LOGIN_URL) self.authority_uri = aad_authority_uri + authority if aad_authority_uri.endswith( "/") else aad_authority_uri + "/" + authority def acquire_authorization_header(self): """Acquire tokens from AAD.""" try: return self._acquire_authorization_header() except (AdalError, KustoClientError) as error: if self.authentication_method is AuthenticationMethod.aad_username_password: kwargs = { "username": self.username, "client_id": self.client_id } elif self.authentication_method is AuthenticationMethod.aad_application_key: kwargs = {"client_id": self.client_id} elif self.authentication_method is AuthenticationMethod.aad_device_login: kwargs = {"client_id": self.client_id} elif self.authentication_method is AuthenticationMethod.aad_application_certificate: kwargs = { "client_id": self.client_id, "thumbprint": self.thumbprint } elif self.authentication_method is AuthenticationMethod.aad_msi: kwargs = self.msi_params elif self.authentication_method is AuthenticationMethod.token_provider: kwargs = {} else: raise error kwargs["resource"] = self.kusto_uri if self.authentication_method is AuthenticationMethod.aad_msi: kwargs["authority"] = AuthenticationMethod.aad_msi.value elif self.authentication_method is AuthenticationMethod.token_provider: kwargs["authority"] = AuthenticationMethod.token_provider.value elif self.auth_context is not None: kwargs["authority"] = self.auth_context.authority.url raise KustoAuthenticationError(self.authentication_method.value, error, **kwargs) def _acquire_authorization_header(self) -> str: # Token was provided by caller if self.authentication_method is AuthenticationMethod.aad_token: return _get_header("Bearer", self.token) if self.authentication_method is AuthenticationMethod.token_provider: caller_token = self.token_provider() if not isinstance(caller_token, str): raise KustoClientError( "Token provider returned something that is not a string [" + str(type(caller_token)) + "]") return _get_header("Bearer", caller_token) # Obtain token from MSI endpoint if self.authentication_method == AuthenticationMethod.aad_msi: token = self.get_token_from_msi() return _get_header_from_dict(token) refresh_token = None if self.authentication_method == AuthenticationMethod.az_cli_profile: stored_token = _get_azure_cli_auth_token() if (TokenResponseFields.REFRESH_TOKEN in stored_token and TokenResponseFields._CLIENT_ID in stored_token and TokenResponseFields._AUTHORITY in stored_token): self.client_id = stored_token[TokenResponseFields._CLIENT_ID] self.username = stored_token[TokenResponseFields.USER_ID] self.authority_uri = stored_token[ TokenResponseFields._AUTHORITY] refresh_token = stored_token[TokenResponseFields.REFRESH_TOKEN] if self.auth_context is None: self.auth_context = AuthenticationContext(self.authority_uri) if refresh_token is not None: token = self.auth_context.acquire_token_with_refresh_token( refresh_token, self.client_id, self.kusto_uri) else: token = self.auth_context.acquire_token(self.kusto_uri, self.username, self.client_id) if token is not None: expiration_date = dateutil.parser.parse( token[TokenResponseFields.EXPIRES_ON]) if expiration_date > datetime.now() + timedelta(minutes=1): return _get_header_from_dict(token) if TokenResponseFields.REFRESH_TOKEN in token: token = self.auth_context.acquire_token_with_refresh_token( token[TokenResponseFields.REFRESH_TOKEN], self.client_id, self.kusto_uri) if token is not None: return _get_header_from_dict(token) # obtain token from AAD if self.authentication_method is AuthenticationMethod.aad_username_password: token = self.auth_context.acquire_token_with_username_password( self.kusto_uri, self.username, self.password, self.client_id) elif self.authentication_method is AuthenticationMethod.aad_application_key: token = self.auth_context.acquire_token_with_client_credentials( self.kusto_uri, self.client_id, self.client_secret) elif self.authentication_method is AuthenticationMethod.aad_device_login: code = self.auth_context.acquire_user_code(self.kusto_uri, self.client_id) print(code[OAuth2DeviceCodeResponseParameters.MESSAGE]) webbrowser.open( code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL]) token = self.auth_context.acquire_token_with_device_code( self.kusto_uri, code, self.client_id) elif self.authentication_method is AuthenticationMethod.aad_application_certificate: token = self.auth_context.acquire_token_with_client_certificate( self.kusto_uri, self.client_id, self.certificate, self.thumbprint) else: raise KustoClientError( "Please choose authentication method from azure.kusto.data.security.AuthenticationMethod" ) return _get_header_from_dict(token) def get_token_from_msi(self) -> dict: try: credentials = MSIAuthentication(**self.msi_params) except Exception as e: raise KustoClientError("Failed to obtain MSI context for [" + str(self.msi_params) + "]\n" + str(e)) return credentials.token
def authenticate_with_device_code(account_name): """Setup storage tokens by authenticating with device code and use management APIs. Args: account_name (str): The storage account name for which to authenticate """ import urllib # pylint: disable=import-outside-toplevel import json # pylint: disable=import-outside-toplevel import os # pylint: disable=import-outside-toplevel from tensorflow.python.platform import ( # pylint: disable=import-outside-toplevel tf_logging as log, ) try: from adal import ( # pylint: disable=import-outside-toplevel AuthenticationContext, ) except ModuleNotFoundError: log.error( "Please install adal library with `python -m pip install -U adal`" "to use the device code authentication method" ) return ctx = AuthenticationContext("https://login.microsoftonline.com/common") storage_resource = "https://management.azure.com/" # Current multi-tenant client registerd in my AzureAD tenant client_id = "8c375311-7f4c-406c-84f8-03dfe11ba2d3" device_code = ctx.acquire_user_code(resource=storage_resource, client_id=client_id) # Display authentication message to user to action in their browser log.warn(device_code["message"]) token_response = ctx.acquire_token_with_device_code( resource=storage_resource, user_code_info=device_code, client_id=client_id ) headers = {"Authorization": "Bearer " + token_response["accessToken"]} subscription_list_req = urllib.request.Request( url="https://management.azure.com/subscriptions?api-version=2016-06-01", headers=headers, ) with urllib.request.urlopen(subscription_list_req) as f: subscriptions = json.load(f) subscriptions = subscriptions["value"] storage_account = None for subscription in subscriptions: url = "https://management.azure.com/subscriptions/{}/providers/Microsoft.Storage/storageAccounts?api-version=2019-04-01".format( subscription["subscriptionId"] ) storage_account_list_req = urllib.request.Request(url=url, headers=headers) with urllib.request.urlopen(storage_account_list_req) as f: storage_accounts = json.load(f) storage_accounts = storage_accounts["value"] account_by_name = [s for s in storage_accounts if s.get("name") == account_name] if any(account_by_name): storage_account = account_by_name[0] break if storage_account is None: log.error( "Couldn't find storage account {} in any " "available subscription".format(account_name) ) return url = "https://management.azure.com/{}/listKeys?api-version=2019-04-01".format( storage_account["id"] ) storage_list_keys_req = urllib.request.Request( url=url, headers=headers, method="POST" ) with urllib.request.urlopen(storage_list_keys_req) as f: account_keys = json.load(f) os.environ["TF_AZURE_STORAGE_KEY"] = account_keys["keys"][0]["value"] log.info( "Successfully set account key environment for {} " "storage account".format(account_name) )
class _AadHelper(object): def __init__(self, kcsb): if any([kcsb.user_token, kcsb.application_token]): self._token = kcsb.user_token or kcsb.application_token self._authentication_method = AuthenticationMethod.aad_token return authority = kcsb.authority_id or "common" self._kusto_cluster = "{0.scheme}://{0.hostname}".format( urlparse(kcsb.data_source)) self._adal_context = AuthenticationContext( "https://login.microsoftonline.com/{0}".format(authority)) self._username = None if all([kcsb.aad_user_id, kcsb.password]): self._authentication_method = AuthenticationMethod.aad_username_password self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58" self._username = kcsb.aad_user_id self._password = kcsb.password elif all([kcsb.application_client_id, kcsb.application_key]): self._authentication_method = AuthenticationMethod.aad_application_key self._client_id = kcsb.application_client_id self._client_secret = kcsb.application_key elif all([ kcsb.application_client_id, kcsb.application_certificate, kcsb.application_certificate_thumbprint ]): self._authentication_method = AuthenticationMethod.aad_application_certificate self._client_id = kcsb.application_client_id self._certificate = kcsb.application_certificate self._thumbprint = kcsb.application_certificate_thumbprint else: self._authentication_method = AuthenticationMethod.aad_device_login self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58" def acquire_authorization_header(self): """Acquire tokens from AAD.""" try: return self._acquire_authorization_header() except AdalError as error: if self._authentication_method is AuthenticationMethod.aad_username_password: kwargs = { "username": self._username, "client_id": self._client_id } elif self._authentication_method is AuthenticationMethod.aad_application_key: kwargs = {"client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_device_login: kwargs = {"client_id": self._client_id} elif self._authentication_method is AuthenticationMethod.aad_application_certificate: kwargs = { "client_id": self._client_id, "thumbprint": self._thumbprint } else: raise error kwargs["resource"] = self._kusto_cluster kwargs["authority"] = self._adal_context.authority.url raise KustoAuthenticationError(self._authentication_method.value, error, **kwargs) def _acquire_authorization_header(self): if self._authentication_method is AuthenticationMethod.aad_token: return _get_header("Bearer", self._token) token = self._adal_context.acquire_token(self._kusto_cluster, self._username, self._client_id) if token is not None: expiration_date = dateutil.parser.parse( token[TokenResponseFields.EXPIRES_ON]) if expiration_date > datetime.now() + timedelta(minutes=1): return _get_header_from_dict(token) if TokenResponseFields.REFRESH_TOKEN in token: token = self._adal_context.acquire_token_with_refresh_token( token[TokenResponseFields.REFRESH_TOKEN], self._client_id, self._kusto_cluster) if token is not None: return _get_header_from_dict(token) if self._authentication_method is AuthenticationMethod.aad_username_password: token = self._adal_context.acquire_token_with_username_password( self._kusto_cluster, self._username, self._password, self._client_id) elif self._authentication_method is AuthenticationMethod.aad_application_key: token = self._adal_context.acquire_token_with_client_credentials( self._kusto_cluster, self._client_id, self._client_secret) elif self._authentication_method is AuthenticationMethod.aad_device_login: code = self._adal_context.acquire_user_code( self._kusto_cluster, self._client_id) print(code[OAuth2DeviceCodeResponseParameters.MESSAGE]) webbrowser.open( code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL]) token = self._adal_context.acquire_token_with_device_code( self._kusto_cluster, code, self._client_id) elif self._authentication_method is AuthenticationMethod.aad_application_certificate: token = self._adal_context.acquire_token_with_client_certificate( self._kusto_cluster, self._client_id, self._certificate, self._thumbprint) else: raise KustoClientError( "Please choose authentication method from azure.kusto.data.security.AuthenticationMethod" ) return _get_header_from_dict(token)
class _MyAadHelper(object): def __init__(self, kusto_cluster, client_id=None, client_secret=None, username=None, password=None, authority=None): self.adal_context = AuthenticationContext( 'https://login.windows.net/{0}'.format(authority or 'microsoft.com')) self.kusto_cluster = kusto_cluster self.client_id = client_id or "db662dc1-0cfe-4e1c-a843-19a68e65be58" self.client_secret = client_secret self.username = username self.password = password def acquire_token(self): """ A method to acquire tokens from AAD. """ # print("my_aad_helper_acquire_token") token_response = self.adal_context.acquire_token( self.kusto_cluster, self.username, self.client_id) if token_response is not None: expiration_date = dateutil.parser.parse( token_response['expiresOn']) if expiration_date > datetime.utcnow() + timedelta(minutes=5): return token_response['accessToken'] if self.client_secret is not None and self.client_id is not None: token_response = self.adal_context.acquire_token_with_client_credentials( self.kusto_cluster, self.client_id, self.client_secret) elif self.username is not None and self.password is not None: token_response = self.adal_context.acquire_token_with_username_password( self.kusto_cluster, self.username, self.password, self.client_id) else: code = self.adal_context.acquire_user_code(self.kusto_cluster, self.client_id) url = code['verification_url'] device_code = code["user_code"].strip() html_str = """<!DOCTYPE html> <html><body> <!-- h1 id="user_code_p"><b>""" + device_code + """</b><br></h1--> <input id="kqlMagicCodeAuthInput" type="text" readonly style="font-weight: bold; border: none;" size = '""" + str( len(device_code)) + """' value='""" + device_code + """'> <button id='kqlMagicCodeAuth_button', onclick="this.style.visibility='hidden';kqlMagicCodeAuthFunction()">Copy code to clipboard and authenticate</button> <script> var kqlMagicUserCodeAuthWindow = null function kqlMagicCodeAuthFunction() { /* Get the text field */ var copyText = document.getElementById("kqlMagicCodeAuthInput"); /* Select the text field */ copyText.select(); /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ // alert("Copied the text: " + copyText.value); var w = screen.width / 2; var h = screen.height / 2; params = 'width='+w+',height='+h kqlMagicUserCodeAuthWindow = window.open('""" + url + """', 'kqlMagicUserCodeAuthWindow', params); } </script> </body></html>""" Display.show(html_str) # webbrowser.open(code['verification_url']) try: token_response = self.adal_context.acquire_token_with_device_code( self.kusto_cluster, code, self.client_id) finally: html_str = """<!DOCTYPE html> <html><body><script> // close authentication window if (kqlMagicUserCodeAuthWindow && kqlMagicUserCodeAuthWindow.opener != null && !kqlMagicUserCodeAuthWindow.closed) { kqlMagicUserCodeAuthWindow.close() } // clear output cell Jupyter.notebook.clear_output(Jupyter.notebook.get_selected_index()) // move to next cell </script></body></html>""" Display.show(html_str) return token_response['accessToken']