def __init__(self, batchToken: str, armToken: str, account: BatchAccount): self.batchCreds = AdalAuthentication( lambda: {'accessToken': batchToken}) self.armCreds = AdalAuthentication(lambda: { 'accessToken': armToken, 'tokenType': 'Bearer' }) self.account = account self.client = batch.BatchExtensionsClient( credentials=self.batchCreds, batch_account=self.account.name, base_url='https://{0}'.format(account.account_endpoint), subscription_id=account.subscription_id, mgmt_credentials=self.armCreds)
def _get_client(self): if os.getenv("USE_MSI", "false").lower() == "true": _logger.info('Using MSI') if "MSI_CLIENT_ID" in os.environ: msi_client_id = os.environ["MSI_CLIENT_ID"] _logger.info('Using client_id: %s', msi_client_id) credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME, client_id=msi_client_id) elif "MSI_OBJECT_ID" in os.environ: msi_object_id = os.environ["MSI_OBJECT_ID"] _logger.info('Using object_id: %s', msi_object_id) credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME, object_id=msi_object_id) elif "MSI_RESOURCE_ID" in os.environ: msi_resource_id = os.environ["MSI_RESOURCE_ID"] _logger.info('Using resource_id: %s', msi_resource_id) credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME, msi_res_id=msi_resource_id) else: credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME) else: self._parse_sp_file() authority = '/'.join([AZURE_AUTHORITY_SERVER.rstrip('/'), self.tenant_id]) _logger.info('Using authority: %s', authority) context = AuthenticationContext(authority) _logger.info('Using vault resource name: %s and client id: %s', VAULT_RESOURCE_NAME, self.client_id) credentials = AdalAuthentication(context.acquire_token_with_client_credentials, VAULT_RESOURCE_NAME, self.client_id, self.client_secret) return KeyVaultClient(credentials)
async def async_setup(hass, config): """Initialize the Azure DNS component.""" # Acquire the Azure AD token. try: context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + config[DOMAIN][CONF_TENANT]) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, RESOURCE, config[DOMAIN][CONF_CLIENTID], config[DOMAIN][CONF_CLIENTSECRET]) except adal.AdalError as error: _LOGGER.error("Failed to acquire Azure AD Credential: %s", error) return False result = await _update_azuredns(config, credentials) if not result: _LOGGER.error("Failed to update Azure DNS record") return False async def update_domain_interval(): """Update the Azure DNS entry.""" await _update_azuredns(config, credentials) async_track_time_interval(hass, update_domain_interval, INTERVAL) return result
def getAADTokenCredentials(cloudType, resource, appId, tenantId, secret): LOGIN_ENDPOINT = cloudType.endpoints.active_directory context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + tenantId) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, resource, appId, secret) return credentials
def __init__(self): # Read the settings from config self.config = configparser.ConfigParser() self.config.read('./settings.ini') self.account_name = self.config['DEFAULT']['ACCOUNT_NAME'] self.resource_group_name = self.config['DEFAULT'][ 'RESOURCE_GROUP_NAME'] self.transform_name = self.config['DEFAULT']['TRANSFORM_NAME'] # Read the transform name for audio analyzer # self.audio_analyzer_transform_name = self.config['DEFAULT']['AUDIO_ANALYZER_TRANSFORM_NAME'] client_id = self.config['DEFAULT']['CLIENT'] key = self.config['DEFAULT']['KEY'] subscription_id = self.config['DEFAULT']['SUBSCRIPTION_ID'] tenant_id = self.config['DEFAULT']['TENANT_ID'] login_endpoint = AZURE_PUBLIC_CLOUD.endpoints.active_directory resource = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id context = adal.AuthenticationContext(login_endpoint + '/' + tenant_id) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, resource, client_id, key) # The AMS Client # You can now use this object to perform different operations to your AMS account. self.client = AzureMediaServices(credentials, subscription_id)
def get_client_from_json_dict(client_class, config_dict, **kwargs): """Return a SDK client initialized with a JSON auth dict. The easiest way to obtain this content is to call the following CLI commands: .. code:: bash az ad sp create-for-rbac --sdk-auth This method will fill automatically the following client parameters: - credentials - subscription_id - base_url Parameters provided in kwargs will override parameters and be passed directly to the client. :Example: .. code:: python from azure.common.client_factory import get_client_from_auth_file from azure.mgmt.compute import ComputeManagementClient config_dict = { "clientId": "ad735158-65ca-11e7-ba4d-ecb1d756380e", "clientSecret": "b70bb224-65ca-11e7-810c-ecb1d756380e", "subscriptionId": "bfc42d3a-65ca-11e7-95cf-ecb1d756380e", "tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e", "activeDirectoryEndpointUrl": "https://login.microsoftonline.com", "resourceManagerEndpointUrl": "https://management.azure.com/", "activeDirectoryGraphResourceId": "https://graph.windows.net/", "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/", "galleryEndpointUrl": "https://gallery.azure.com/", "managementEndpointUrl": "https://management.core.windows.net/" } client = get_client_from_json_dict(ComputeManagementClient, config_dict) .. versionadded:: 1.1.7 :param client_class: A SDK client class :param dict config_dict: A config dict. :return: An instanciated client """ parameters = { 'subscription_id': config_dict.get('subscriptionId'), 'base_url': config_dict.get('resourceManagerEndpointUrl'), } if 'credentials' not in kwargs: authority_url = (config_dict['activeDirectoryEndpointUrl'] + '/' + config_dict['tenantId']) context = adal.AuthenticationContext(authority_url, api_version=None) parameters['credentials'] = AdalAuthentication( context.acquire_token_with_client_credentials, config_dict['resourceManagerEndpointUrl'], config_dict['clientId'], config_dict['clientSecret'] ) parameters.update(kwargs) return _instantiate_client(client_class, **parameters)
def __init__(self): # Read the settings from config self.config = configparser.ConfigParser() self.config.read('./settings.ini') self.account_name = self.config['DEFAULT']['ACCOUNT_NAME'] self.resource_group_name = self.config['DEFAULT'][ 'RESOURCE_GROUP_NAME'] self.transform_name = self.config['DEFAULT']['TRANSFORM_NAME'] self.content_key_policy_name = self.config['DEFAULT'][ 'CONTENT_KEY_POLICY_NAME'] self.content_key_identifier_claim_type = self.config['DEFAULT'][ 'CONTENT_KEY_IDENTIFIER_CLAIM_TYPE'] self.issuer = self.config['DEFAULT']['ISSUER'] self.audience = self.config['DEFAULT']['AUDIENCE'] self.token_sign_key = b64decode( self.config['DEFAULT']['SYMMETRIC_KEY']) client_id = self.config['DEFAULT']['CLIENT'] key = self.config['DEFAULT']['KEY'] subscription_id = self.config['DEFAULT']['SUBSCRIPTION_ID'] tenant_id = self.config['DEFAULT']['TENANT_ID'] login_endpoint = AZURE_PUBLIC_CLOUD.endpoints.active_directory resource = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id context = adal.AuthenticationContext(login_endpoint + '/' + tenant_id) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, resource, client_id, key) # The AMS Client # You can now use this object to perform different operations to your AMS account. self.client = AzureMediaServices(credentials, subscription_id)
def get_credentials(): LOGIN_ENDPOINT = AZURE_PUBLIC_CLOUD.endpoints.active_directory RESOURCE = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + TENANT_ID) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, RESOURCE, CLIENT, KEY) return credentials
def _get_client(self): authority = '/'.join([AZURE_AUTHORITY_SERVER.rstrip('/'), self.tenant_id]) _logger.info('Using authority: %s', authority) context = AuthenticationContext(authority) _logger.info('Using vault resource name: %s and client id: %s', VAULT_RESOURCE_NAME, self.client_id) credentials = AdalAuthentication(context.acquire_token_with_client_credentials, VAULT_RESOURCE_NAME, self.client_id, self.client_secret) return KeyVaultClient(credentials)
def GetCredentialsForResource(self, resource): try: return self._resource_credentials[resource] except KeyError: ans = AdalAuthentication( self.context.acquire_token_with_client_credentials, resource, self.client_id, self.secret) self._resource_credentials[resource] = ans return ans
def auth(): # Intialize the user-specific variables that will be used during run-time global CREDENTIALS global USERNAME global GRAPH_DATA global TOKEN global AUTH_TOKEN code = flask.request.args['code'] state = flask.request.args['state'] client_id = 'fb20d6fe-ce09-449a-b096-90f229943863' client_secret = '9bPMwvy7HztrwVkkCR08BOPMbPUb5Ze8MqMVZOwGTMQ=' # GET THE MICROSOFT GRAPH ACCESS TOKEN resource = 'https://graph.microsoft.com' context = adal.AuthenticationContext(AUTHORITY_URL) auth_token = context.acquire_token_with_authorization_code( code, REDIRECT_URI, resource, client_id, client_secret) flask.session['auth_access_token'] = auth_token['accessToken'] AUTH_TOKEN = auth_token['accessToken'] # GET THE AZURE RESOURCE MANAGEMENT ACCESS TOKEN (USED TO MAKE REST CALLS MANUALLY) resource = 'https://management.azure.com' context = adal.AuthenticationContext(AUTHORITY_URL) manage_token = context.acquire_token_with_authorization_code( code, REDIRECT_URI, resource, client_id, client_secret) flask.session['access_token'] = manage_token['accessToken'] TOKEN = manage_token['accessToken'] # GET THE AZURE RESOURCE MANAGEMENT CREDENTIALS (USED WITH SDK FOR PYTHON) CREDENTIALS = AdalAuthentication( context.acquire_token_with_client_credentials, config.MANAGE_RESOURCE, config.CLIENT_ID, config.CLIENT_SECRET) # MAKE A MANUAL REST CALL CALL TO THE GRAPH API TO GET USER INFO WHICH WILL ALWAYS BE USED! endpoint = config.AUTH_RESOURCE + '/' + config.API_VERSION + '/me/' # The specific endpoint for the 'Read User Info' rest call, look in Microsoft documentation for this http_headers = { 'Authorization': flask.session.get( 'auth_access_token' ), # Headers to be injected, include the authorization token 'User-Agent': 'duolca_app', 'Accept': 'application/json', 'Content-Type': 'application/json', 'client-request-id': str(uuid.uuid4()) } GRAPH_DATA = requests.get(endpoint, headers=http_headers, stream=False).json() flask.session['username'] = GRAPH_DATA['givenName'] USERNAME = GRAPH_DATA['givenName'] return flask.redirect('/home')
def main(event: func.EventGridEvent): result = json.dumps({ 'id': event.id, 'data': event.get_json(), 'topic': event.topic, 'subject': event.subject, 'event_type': event.event_type, }) context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + TENANT_ID) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, RESOURCE, CLIENT, KEY) # You can now use this object to perform different operations to your AMS account. client = AzureMediaServices(credentials, SUBSCRIPTION_ID) logging.info("signed in to ams") logging.info('assest list %s', client.assets.list(RESOUCE_GROUP_NAME, ACCOUNT_NAME).get(0)) logging.info('Python EventGrid trigger processed an event: %s', result)
def __create_media_service_client(self): LOGIN_ENDPOINT = AZURE_PUBLIC_CLOUD.endpoints.active_directory RESOURCE = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id context = adal.AuthenticationContext( LOGIN_ENDPOINT + '/' + Config.AAD_TENANT_ID ) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, RESOURCE, Config.AAD_CLIENT_ID, Config.AAD_SECRET ) self.media_service_client = AzureMediaServices( credentials, Config.SUBSCRIPTION_ID )
def get_access_tokens(tenant_id, client_id, client_secret): context = adal.AuthenticationContext(f'https://login.microsoftonline.com/{tenant_id}', validate_authority=True) cred1 = AdalAuthentication( context.acquire_token_with_client_credentials, 'https://management.core.windows.net/', client_id, client_secret) cred2 = AdalAuthentication( context.acquire_token_with_client_credentials, '2ff814a6-3304-4ab8-85cb-cd0e6f879c1d', client_id, client_secret) return \ cred1.signed_session(None).headers.get(cred1.header).replace('Bearer ', ''), \ cred2.signed_session(None).headers.get(cred2.header).replace('Bearer ', '')
def _get_client(self): if os.getenv("USE_MSI", "false").lower() == "true": _logger.info('Using MSI') if "MSI_CLIENT_ID" in os.environ: msi_client_id = os.environ["MSI_CLIENT_ID"] _logger.info('Using client_id: %s', msi_client_id) credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME, client_id=msi_client_id) elif "MSI_OBJECT_ID" in os.environ: msi_object_id = os.environ["MSI_OBJECT_ID"] _logger.info('Using object_id: %s', msi_object_id) credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME, object_id=msi_object_id) elif "MSI_RESOURCE_ID" in os.environ: msi_resource_id = os.environ["MSI_RESOURCE_ID"] _logger.info('Using resource_id: %s', msi_resource_id) credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME, msi_res_id=msi_resource_id) else: credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME) else: if os.getenv("USE_ENV", "false").lower() == "true": self._parse_sp_env() else: self._parse_sp_file() # azure.json file will have "msi" as the client_id and client_secret # if the node is running managed identity if self.client_id == "msi" and self.client_secret == "msi": _logger.info('Using MSI') # refer _parse_sp_file, potentially we could have mi client id from sp if self.user_assigned_identity_id != "": _logger.info('Using client_id: %s', self.user_assigned_identity_id) credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME, client_id=self.user_assigned_identity_id) else: credentials = MSIAuthentication(resource=VAULT_RESOURCE_NAME) else: authority = '/'.join([AZURE_AUTHORITY_SERVER.rstrip('/'), self.tenant_id]) _logger.info('Using authority: %s', authority) context = AuthenticationContext(authority) _logger.info('Using vault resource name: %s and client id: %s', VAULT_RESOURCE_NAME, self.client_id) credentials = AdalAuthentication(context.acquire_token_with_client_credentials, VAULT_RESOURCE_NAME, self.client_id, self.client_secret) return KeyVaultClient(credentials)
def get_local_credentials(resource=None): from msrestazure.azure_active_directory import AdalAuthentication logger = logging.getLogger(__name__) data = json.load(open("./sp.json")) if not ('clientId' in data or 'clientSecret' in data or 'subscriptionId' in data or 'tenantId' in data): logger.error( "did not find either clientId, clientSecret, subscriptionId of tenantId in file" ) return None, None else: logger.debug( f"found clientId={data['clientId']} in sub={data['subscriptionId']}" ) if not resource: resource = "https://management.core.windows.net" server = resource + '/' + data['tenantId'] context = adal.AuthenticationContext(server) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id, data['clientId'], data['clientSecret']) return credentials, data['subscriptionId']
#region Key Vault Parameters #-------------------------------------------------------- # Setup Azure Key Vault Authentication Parameters #-------------------------------------------------------- LOGIN_ENDPOINT = AZURE_PUBLIC_CLOUD.endpoints.active_directory RESOURCE_URI = 'https://vault.azure.net' VAULT_URI = 'https://<KeyVaultName>.vault.azure.net/' #Replace with Azure Key Vault URI, Should be input argument #-------------------------------------------------------- #endregion #region Key Vault Connection #-------------------------------------------------------- # Connect to Azure Key Vault as a Client #-------------------------------------------------------- context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + TENANT_ID) credentials = AdalAuthentication(context.acquire_token_with_client_credentials, RESOURCE_URI, CLIENT_ID, KEY) kvClient = KeyVaultClient(credentials) #--------------------------------------------------------- #endregion #region Get Key Vault Secret #--------------------------------------------------------- # Retrieve Key Vault Secrets #--------------------------------------------------------- keyValue = ( kvClient.get_secret(VAULT_URI, '<Key_Name>', '') ).value #Replace with correct Key Vault Secret Key Name, Should be input argument #--------------------------------------------------------- #endregion
def test_adal_authentication(self): def success_auth(): return {'tokenType': 'https', 'accessToken': 'cryptictoken'} credentials = AdalAuthentication(success_auth) session = credentials.signed_session() self.assertEqual(session.headers['Authorization'], 'https cryptictoken') def error(): raise adal.AdalError("You hacker", {}) credentials = AdalAuthentication(error) with self.assertRaises(AuthenticationError) as cm: session = credentials.signed_session() def expired(): raise adal.AdalError("Too late", {'error_description': "AADSTS70008: Expired"}) credentials = AdalAuthentication(expired) with self.assertRaises(TokenExpiredError) as cm: session = credentials.signed_session() def connection_error(): raise ConnectionError("Plug the network") credentials = AdalAuthentication(connection_error) with self.assertRaises(AuthenticationError) as cm: session = credentials.signed_session()
def get_client_from_auth_file(clientclass, auth_path=None, **kwargs): """Return a SDK client initialized with auth information in azureauth.properties. The path will be given using the environment variable AZURE_AUTH_LOCATION. File must be UTF-8 compliant. This method will fill automatically the following client parameters: - credentials - subscription_id - base_url Parameters provided in kwargs will override CLI parameters and be passed directly to the client. :Example: .. code:: python from azure.common.client_factory import get_client_from_auth_file from azure.mgmt.compute import ComputeManagementClient client = get_client_from_auth_file(ComputeManagementClient) Example of file: .. code:: text # sample management library properties file subscription=15dbcfa8-4b93-4c9a-881c-6189d39f04d4 client=a2ab11af-01aa-4759-8345-7803287dbd39 key=password tenant=43413cc1-5886-4711-9804-8cfea3d1c3ee managementURI=https://management.core.windows.net/ baseURL=https://management.azure.com/ authURL=https://login.windows.net/ graphURL=https://graph.windows.net/ .. versionadded:: 1.1.7 :param clientclass: A SDK client class :param str auth_path: Path to azureauth.properties :return: An instanciated client :raises: KeyError if AZURE_AUTH_LOCATION is not an environment variable and no path is provided :raises: FileNotFoundError if provided file path does not exists """ auth_path = auth_path or os.environ['AZURE_AUTH_LOCATION'] with io.open(auth_path, 'r', encoding='utf-8') as auth_fd: content_list = [ line.strip() for line in auth_fd.readlines() if line[0] != '#' and '=' in line ] config_dict = dict([tuple(line.split('=', 1)) for line in content_list]) parameters = { 'subscription_id': config_dict.get('subscription'), 'base_url': config_dict.get('baseURL'), } if 'credentials' not in kwargs: authority_url = (config_dict['authURL'] + '/' + config_dict['tenant']) context = adal.AuthenticationContext(authority_url, api_version=None) parameters['credentials'] = AdalAuthentication( context.acquire_token_with_client_credentials, config_dict['managementURI'], config_dict['client'], config_dict['key']) parameters.update(kwargs) return clientclass(**parameters)
#### STORAGE #### # Values from .env and the blob url # For this sample you will use the storage account key to create and access assets # The SAS URL is not used here storage_account_name = os.getenv('STORAGEACCOUNTNAME', 'default_val') storage_account_key = os.getenv('STORAGEACCOUNTKEY', 'default_val') storage_blob_url = 'https://' + storage_account_name + '.blob.core.windows.net/' # Active Directory LOGIN_ENDPOINT = AZURE_PUBLIC_CLOUD.endpoints.active_directory RESOURCE = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id # Establish credentials context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + tenant_id) credentials = AdalAuthentication(context.acquire_token_with_client_credentials, RESOURCE, client_id, key) # The file you want to upload. For this example, put the file in the same folder as this script. # The file ignite.mp4 has been provided for you. source_file = "ignite.mp4" # Generate a random number that will be added to the naming of things so that you don't have to keep doing this during testing. thisRandom = random.randint(0, 9999) # Set the attributes of the input Asset using the random number in_asset_name = 'inputassetName' + str(thisRandom) in_alternate_id = 'inputALTid' + str(thisRandom) in_description = 'inputdescription' + str(thisRandom) # Create an Asset object # From the SDK # Asset(*, alternate_id: str = None, description: str = None, container: str = None, storage_account_name: str = None, **kwargs) -> None
def get_app_credentials(resource, tenant_id='common'): context = adal.AuthenticationContext(g.aad_endpoint + tenant_id) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, resource, g.clientId, g.clientSecret) return credentials
def get_user_credentials(code, redirect_uri, resource, tenant_id='common'): context = adal.AuthenticationContext(g.aad_endpoint + tenant_id) credentials = AdalAuthentication( context.acquire_token_with_authorization_code, code, redirect_uri, resource, g.clientId, g.clientSecret) return credentials
import adal import os from msrestazure.azure_active_directory import AdalAuthentication from azure.mgmt.resource import ResourceManagementClient # Service Principal tenant = os.environ['AZURE_TENANT_ID'] client_id = os.environ['AZURE_CLIENT_ID'] password = os.environ['AZURE_CLIENT_SECRET'] # Public Azure - default values authentication_endpoint = 'https://login.microsoftonline.com/' azure_endpoint = 'https://management.azure.com/' context = adal.AuthenticationContext(authentication_endpoint + tenant) credentials = AdalAuthentication(context.acquire_token_with_client_credentials, azure_endpoint, client_id, password) subscription_id = os.environ['AZURE_SUBSCRIPTION_ID'] resource_client = ResourceManagementClient(credentials, subscription_id, base_url=azure_endpoint) client = ResourceManagementClient(credentials, subscription_id) resource_group_params = {'location': 'Southindia'} # Creating resource group client.resource_groups.create_or_update('azure-sample-group', resource_group_params)
def aksauth_connect(cmd, resource_group, cluster_name, tenant, username, password): subscription = get_subscription_id(cmd.cli_ctx) authority_url = ('https://login.microsoftonline.com/' + tenant) context = adal.AuthenticationContext( authority_url, api_version=1.0, ) LOGGER.info("Authenticating to AAD using ARM Resource and Default Client ID") #Create credentials object from our adal username and password flow. credentials = AdalAuthentication( context.acquire_token_with_username_password, 'https://management.azure.com/', username, password, '04b07795-8ddb-461a-bbee-02f9e1bf7b46' ) LOGGER.info("Getting Kubeconfig Skeleton") #Get the skeleton kubeconfig client = ContainerServiceClient(credentials, subscription) credentialResults = client.managed_clusters.list_cluster_user_credentials(resource_group, cluster_name) LOGGER.info("Write Kubeconfig Skeleton to temp file") #Write skeleton kubeconfig to temp file fd, temp_path = tempfile.mkstemp() additional_file = os.fdopen(fd, 'w+t') try: additional_file.write(credentialResults.kubeconfigs[0].value.decode(encoding='UTF-8')) additional_file.flush() finally: additional_file.close() LOGGER.info("Load Kubeconfig Skeleton to dict") #Open skeleton kubeconfig into a dict and extract server, client and context name with open(temp_path) as file: kconfig = yaml.load(file, Loader=yaml.FullLoader) apiServer = kconfig.get('users')[0].get('user').get('auth-provider').get('config').get('apiserver-id') clientId = kconfig.get('users')[0].get('user').get('auth-provider').get('config').get('client-id') contextName = kconfig.get('contexts')[0].get('name') os.remove(temp_path) LOGGER.info("Authenticate with client on behalf of user to API Server App") #Generate access token, refresh token, expiry details using client and server token = context.acquire_token_with_username_password( resource=apiServer, username=username, password=password, client_id=clientId) LOGGER.info("Subbing in User Identity details into Kubeconfig dict") #Sub in above into kubeconfig dict kconfig['users'][0]['user']['auth-provider']['config']['access-token']=token['accessToken'] kconfig['users'][0]['user']['auth-provider']['config']['refresh-token']=token['refreshToken'] kconfig['users'][0]['user']['auth-provider']['config']['expires-in']=str(token['expiresIn']) kconfig['users'][0]['user']['auth-provider']['config']['expires-on']=token['expiresOn'] LOGGER.info("Write Kubeconfig dict to temp file") #Write kubeconfig dict to temp file fd1, temp_path1 = tempfile.mkstemp() with open(temp_path1, 'w') as file: documents = yaml.dump(kconfig, file) #Get default kubeconfig location kconfigPath = str(Path.home()) + os.sep + '.kube' + os.sep + 'config' LOGGER.info("Check if ddefault Kubeconfig exists") #Create empty kubeconfig and path if it doesn't exist if os.path.exists(kconfigPath) != True: os.makedirs(os.path.dirname(kconfigPath), exist_ok=True) with open(kconfigPath, "w") as f: f.write("") LOGGER.info("merge_kubernetes_configurations temp kubeconfig with default kuebconfig") #Reuse Azure's method to merge our new kubeconfig with the existing one merge_kubernetes_configurations(kconfigPath, temp_path1, True, contextName)
def video_analyze(): """VideoAnalyze. This will analyze a video and download insights for video analysis """ # Your configurations for your AMS account account_name = 'ams account' resource_group_name = 'ResourceGroup' subscription_id = '00000000-0000-0000-0000-000000000000' aad_client_id = '00000000-0000-0000-0000-000000000000' aad_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' tenant_id = 'tenant domain or tenant id' # Your input file name and output folder name for encoding input_mp4_file_name = 'ignite.mp4' input_mp4_files_baseurl = 'https://shigeyfampdemo.azurewebsites.net/videos/' input_mp4_files = ['ignite.mp4'] output_folder_name = 'output' transform_name = 'MyVideoAnalyzerTransformName' # The Azure Media Services (AMS) Client # You can now use this object to perform different operations to your AMS account. login_endpoint = AZURE_PUBLIC_CLOUD.endpoints.active_directory resource = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id context = adal.AuthenticationContext(login_endpoint + '/' + tenant_id) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, resource, aad_client_id, aad_secret) client = AzureMediaServices(credentials, subscription_id) # Creating a unique suffix so that we don't have name collisions if you run the sample # multiple times without cleaning up. uniqueness = str(uuid.uuid1()) job_name = 'job-{}'.format(uniqueness) output_asset_name = 'output-{}'.format(uniqueness) input_asset_name = 'input-{}'.format(uniqueness) # Ensure that you have the desired video analyzer Transform. This is really a one time setup operation. get_or_create_transform(client, resource_group_name, account_name, transform_name, VideoAnalyzerPreset(audio_language='en-US')) # Create a new job input # Option 1) Create a new job input with Asset and upload the specified local video file into it. #create_input_asset(client, resource_group_name, account_name, input_asset_name, input_mp4_file_name) #job_input = JobInputAsset(asset_name = inputasset_name) # Option 2) Create a new job input with HTTP job_input = JobInputHttp(base_uri=input_mp4_files_baseurl, files=input_mp4_files) # Output from the encoding Job must be written to an Asset, so let's create one output_asset = create_output_asset(client, resource_group_name, account_name, output_asset_name) job = submit_job(client, resource_group_name, account_name, transform_name, job_name, job_input, output_asset.name) # In this demo code, we will poll for Job status # Polling is not a recommended best practice for production applications because of the latency it introduces. # Overuse of this API may trigger throttling. Developers should instead use Event Grid. job = wait_for_job_to_finish(client, resource_group_name, account_name, transform_name, job_name) if job.state == JobState.finished: print('Job finished.') download_output_asset(client, resource_group_name, account_name, output_asset.name, output_folder_name) print('Done.')
def get_client_from_json_dict(client_class, config_dict, **kwargs): """Return a SDK client initialized with a JSON auth dict. The easiest way to obtain this content is to call the following CLI commands: .. code:: bash az ad sp create-for-rbac --sdk-auth This method will fill automatically the following client parameters: - credentials - subscription_id - base_url - tenant_id Parameters provided in kwargs will override parameters and be passed directly to the client. :Example: .. code:: python from azure.common.client_factory import get_client_from_auth_file from azure.mgmt.compute import ComputeManagementClient config_dict = { "clientId": "ad735158-65ca-11e7-ba4d-ecb1d756380e", "clientSecret": "b70bb224-65ca-11e7-810c-ecb1d756380e", "subscriptionId": "bfc42d3a-65ca-11e7-95cf-ecb1d756380e", "tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e", "activeDirectoryEndpointUrl": "https://login.microsoftonline.com", "resourceManagerEndpointUrl": "https://management.azure.com/", "activeDirectoryGraphResourceId": "https://graph.windows.net/", "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/", "galleryEndpointUrl": "https://gallery.azure.com/", "managementEndpointUrl": "https://management.core.windows.net/" } client = get_client_from_json_dict(ComputeManagementClient, config_dict) .. versionadded:: 1.1.7 :param client_class: A SDK client class :param dict config_dict: A config dict. :return: An instantiated client """ import adal from msrestazure.azure_active_directory import AdalAuthentication is_graphrbac = client_class.__name__ == 'GraphRbacManagementClient' is_keyvault = client_class.__name__ == 'KeyVaultClient' parameters = { 'subscription_id': config_dict.get('subscriptionId'), 'base_url': config_dict.get('resourceManagerEndpointUrl'), 'tenant_id': config_dict.get('tenantId') # GraphRbac } if is_graphrbac: parameters['base_url'] = config_dict['activeDirectoryGraphResourceId'] if 'credentials' not in kwargs: # Get the right resource for Credentials if is_graphrbac: resource = config_dict['activeDirectoryGraphResourceId'] elif is_keyvault: resource = "https://vault.azure.net" else: if "activeDirectoryResourceId" not in config_dict and 'resourceManagerEndpointUrl' not in config_dict: raise ValueError( "Need activeDirectoryResourceId or resourceManagerEndpointUrl key" ) resource = config_dict.get( 'activeDirectoryResourceId', config_dict['resourceManagerEndpointUrl']) authority_url = config_dict['activeDirectoryEndpointUrl'] is_adfs = bool(re.match('.+(/adfs|/adfs/)$', authority_url, re.I)) if is_adfs: authority_url = authority_url.rstrip( '/' ) # workaround: ADAL is known to reject auth urls with trailing / else: authority_url = authority_url + '/' + config_dict['tenantId'] context = adal.AuthenticationContext(authority_url, api_version=None, validate_authority=not is_adfs) parameters['credentials'] = AdalAuthentication( context.acquire_token_with_client_credentials, resource, config_dict['clientId'], config_dict['clientSecret']) parameters.update(kwargs) return _instantiate_client(client_class, **parameters)
def main(event: func.EventGridEvent): result = json.dumps({ 'id': event.id, 'data': event.get_json(), 'topic': event.topic, 'subject': event.subject, 'event_type': event.event_type, }) logging.info('Python EventGrid trigger processed an event: %s', result) blob_url = event.get_json().get('url') logging.info('blob URL: %s', blob_url) blob_name = blob_url.split("/")[-1].split("?")[0] logging.info('blob name: %s', blob_name) origin_container_name = blob_url.split("/")[-2].split("?")[0] logging.info('container name: %s', origin_container_name) storage_account_name = blob_url.split("//")[1].split(".")[0] logging.info('storage account name: %s', storage_account_name) ams_account_name = os.getenv('ACCOUNTNAME') resource_group_name = os.getenv('RESOURCEGROUP') subscription_id = os.getenv('SUBSCRIPTIONID') client_id = os.getenv('AZURE_CLIENT_ID') client_secret = os.getenv('AZURE_CLIENT_SECRET') TENANT_ID = os.getenv('AZURE_TENANT_ID') storage_blob_url = 'https://' + storage_account_name + '.blob.core.windows.net/' transform_name = 'faceredact' LOGIN_ENDPOINT = AZURE_PUBLIC_CLOUD.endpoints.active_directory RESOURCE = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id logging.info('login_endpoint: %s', LOGIN_ENDPOINT) logging.info('tenant_id: %s', TENANT_ID) out_asset_name = 'faceblurringOutput_' + datetime.utcnow().strftime( "%m-%d-%Y_%H:%M:%S") out_alternate_id = 'faceblurringOutput_' + datetime.utcnow().strftime( "%m-%d-%Y_%H:%M:%S") out_description = 'Redacted video with blurred faces' context = adal.AuthenticationContext(LOGIN_ENDPOINT + "/" + TENANT_ID) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, RESOURCE, client_id, client_secret) client = AzureMediaServices(credentials, subscription_id) output_asset = Asset(alternate_id=out_alternate_id, description=out_description) client.assets.create_or_update(resource_group_name, ams_account_name, out_asset_name, output_asset) token_credential = DefaultAzureCredential() datalake_service_client = DataLakeServiceClient( account_url=storage_blob_url, credential=token_credential) delegation_key = datalake_service_client.get_user_delegation_key( key_start_time=datetime.utcnow(), key_expiry_time=datetime.utcnow() + timedelta(hours=1)) sas_token = generate_file_sas(account_name=storage_account_name, file_system_name=origin_container_name, directory_name="", file_name=blob_name, credential=delegation_key, permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), protocol="https") sas_url = "{}?{}".format(blob_url, sas_token) logging.info(sas_url) job_name = 'Faceblurring-job_' + datetime.utcnow().strftime( "%m-%d-%Y_%H:%M:%S") job_input = JobInputHttp(label="Video_asset", files=[sas_url]) job_output = JobOutputAsset(asset_name=out_asset_name) job_parameters = Job(input=job_input, outputs=[job_output]) client.jobs.create(resource_group_name, ams_account_name, transform_name, job_name, parameters=job_parameters)
logging.info("Creating compartment Admins group") newCompartmentGroup = identity.create_group( oci.identity.models.CreateGroupDetails( compartment_id=tenant_compartment_id, name=newCompartmentName + "-Admins", description=newCompartmentName + "-Admins")).data pks12_cert = crypto.load_pkcs12( automationassets.get_automation_certificate("AzureRunAsCertificate")) pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM, pks12_cert.get_privatekey()) thumbprint = automationConnection["CertificateThumbprint"] context = adal.AuthenticationContext( AZURE_PUBLIC_CLOUD.endpoints.active_directory + '/' + AZTenantId) credentials = AdalAuthentication( lambda: context.acquire_token_with_client_certificate( "https://graph.windows.net", automationConnection["ApplicationId"], pem_pkey, thumbprint)) graphrbac_client = GraphRbacManagementClient(credentials, AZTenantId) AZgrp_name = "cloud-" + newCompartmentName + "-Admins" AZgrp = next( graphrbac_client.groups.list(filter="startswith(displayName,'" + AZgrp_name + "')"), None) if AZgrp is None: graphrbac_client.groups.create( GroupCreateParameters(display_name=AZgrp_name, mail_nickname=AZgrp_name)) logging.info("Creating azure AD group for admins") else: logging.warning("Azure AD group for admins already exists")
compartment_id=newCompartmentParent.id, name=newCompartmentName, description=newCompartmentName)).data logging.info("New compartment: %s" % newCompartment) logging.info("Creating compartment Admins group") newCompartmentGroup = identity.create_group( oci.identity.models.CreateGroupDetails( compartment_id=tenant_compartment_id, name=newCompartmentName + "-Admins", description=newCompartmentName + "-Admins")).data context = adal.AuthenticationContext( AZURE_PUBLIC_CLOUD.endpoints.active_directory + '/' + AZTenantId) credentials = AdalAuthentication( context.acquire_token_with_client_credentials, "https://graph.windows.net", automationassets.get_automation_variable('AzutomationAccountSPId'), automationassets.get_automation_variable('AutomationAccountSP_Key')) graphrbac_client = GraphRbacManagementClient(credentials, AZTenantId) AZgrp_name = "cloud-" + newCompartmentName + "-Admins" AZgrp = next( graphrbac_client.groups.list(filter="startswith(displayName,'" + AZgrp_name + "')"), None) if AZgrp is None: graphrbac_client.groups.create( GroupCreateParameters(display_name=AZgrp_name, mail_nickname=AZgrp_name)) logging.info("Creating azure AD group for admins") else: logging.warning("Azure AD group for admins already exists")