def test_refresh_aadtokencredentials_existing_session(user_password):
    user, password = user_password

    context = adal.AuthenticationContext(
        'https://login.microsoftonline.com/common')
    token = context.acquire_token_with_username_password(
        'https://management.core.windows.net/', user, password,
        '04b07795-8ddb-461a-bbee-02f9e1bf7b46')
    creds = AADTokenCredentials(token)

    root_session = Session()

    creds.signed_session(root_session)

    response = root_session.get(
        "https://management.azure.com/subscriptions?api-version=2016-06-01")
    response.raise_for_status()  # Should never raise

    # Hacking the token time
    creds.token['expires_on'] = time.time() - 10
    creds.token['expires_at'] = creds.token['expires_on']

    try:
        creds.signed_session(root_session)
        response = root_session.get(
            "https://management.azure.com/subscriptions?api-version=2016-06-01"
        )
        pytest.fail("Requests should have failed")
    except oauthlib.oauth2.rfc6749.errors.TokenExpiredError:
        creds.refresh_session(root_session)
        response = root_session.get(
            "https://management.azure.com/subscriptions?api-version=2016-06-01"
        )
        response.raise_for_status()  # Should never raise
Example #2
0
 def authenticate(self, tenant_id, scope):
     app = adal.AuthenticationContext(authority=self.url + tenant_id)
     token = None
     token = app.acquire_token_with_client_credentials(
         scope, self.client_id, self.secret)
     print(token)
     return AADTokenCredentials(token, self.client_id)
    def retrieveToken(self):
        """
        Authenticate using service principal w/ key.
        """
        if self.resource_uri != "":

            client_id = ""
            client_secret = ""
            authority_host_uri = ""
            tenant = ""
            # TODO: get this from key vault
            with open("metadata.json", "r") as f:
                data = json.load(f)
                client_id = data['CLIENT_ID']
                client_secret = data['CLIENT_SECRET']
                authority_host_uri = data["AUTHORITY_HOST_URI"]
                tenant = data["TENANT"]

            authority_uri = authority_host_uri + '/' + tenant
            resource_uri = self.resource_uri

            context = adal.AuthenticationContext(authority_uri,
                                                 api_version=None)
            self.token = context.acquire_token_with_client_credentials(
                resource_uri, client_id, client_secret)
            credentials = AADTokenCredentials(self.token, client_id)
    def create(self, secrets: Dict) -> AADTokenCredentials:
        result = AADTokenCredentials(
            token={"accessToken": secrets['access_token']},
            client_id=secrets.get('client_id'),
            cloud_environment=secrets.get('cloud'))

        return result
    def get_client_for_resource(self,
                                resource='https://management.core.windows.net/'
                                ):
        import adal
        from msrestazure.azure_active_directory import AADTokenCredentials

        # https://github.com/Azure-Samples/key-vault-python-authentication/blob/master/authentication_sample.py
        # create an adal authentication context
        auth_context = adal.AuthenticationContext(
            'https://login.microsoftonline.com/%s' % self.get_tenantid())

        # using the XPlat command line client id as it is available across all tenants and subscriptions
        # this would be replaced by your app id
        xplat_client_id = '04b07795-8ddb-461a-bbee-02f9e1bf7b46'

        user_code_info = auth_context.acquire_user_code(
            resource, xplat_client_id)

        print(user_code_info['message'])
        #try:
        #    import webbrowser
        #     webbrowser.open_new('https://microsoft.com/devicelogin?input='+ user_code_info['user_code'])
        # except:
        #    pass

        token = auth_context.acquire_token_with_device_code(
            resource=resource,
            client_id=xplat_client_id,
            user_code_info=user_code_info)

        return AADTokenCredentials(token, xplat_client_id)
Example #6
0
    def update_batch_and_storage_client_creds(self, batch_auth_token,
                                              mgmt_auth_token):

        self.batchCredentials = AADTokenCredentials(
            batch_auth_token,
            cloud_environment=self.aad_environment_provider.
            getEnvironmentForId(self.aad_environment_id),
            tenant=self.aad_tenant_name)
        self.mgmtCredentials = AADTokenCredentials(
            mgmt_auth_token,
            cloud_environment=self.aad_environment_provider.
            getEnvironmentForId(self.aad_environment_id),
            tenant=self.aad_tenant_name)
        self._client._mgmt_credentials = self.mgmtCredentials
        self._client._client.creds = self.batchCredentials

        self.storage_mgmt_client._client.creds = self.mgmtCredentials
def fetch_aad_token_credentials(client_id, client_secret, authority_uri,
                                resource_uri):
    mgmt_token = fetch_aad_token(client_id, client_secret, authority_uri,
                                 resource_uri)
    try:
        return AADTokenCredentials(mgmt_token, client_id)
    except Exception as e:
        sys.exit("Error occured while fetching credentials: " + str(e))
Example #8
0
def update_batch_and_storage_client_creds(batch_auth_token, mgmt_auth_token,
                                          environment_provider,
                                          aad_environment_id):
    global batch_client
    batchCredentials = AADTokenCredentials(
        batch_auth_token,
        cloud_environment=environment_provider.getEnvironmentForId(
            aad_environment_id),
        tenant=aadTenant)
    mgmtCredentials = AADTokenCredentials(
        mgmt_auth_token,
        cloud_environment=environment_provider.getEnvironmentForId(
            aad_environment_id),
        tenant=aadTenant)

    batch_client._client._mgmt_credentials = mgmtCredentials
    batch_client._client.creds = batchCredentials
    def create(self, secrets: Secrets) -> AADTokenCredentials:
        _cloud = cloud.get_or_raise(secrets['azure_cloud'])
        result = AADTokenCredentials(
            {"accessToken": secrets['access_token']},
            secrets['client_id'],
            cloud_environment=_cloud)

        return result
Example #10
0
    def acquire_token_with_username_password(self, authority, resource, username, password, client_id, tenant):
        authority_uri = authority

        if tenant is not None:
            authority_uri = authority + '/' + tenant

        context = AuthenticationContext(authority_uri)
        token_response = context.acquire_token_with_username_password(resource, username, password, client_id)
        return AADTokenCredentials(token_response)
    def __do_refresh_token(self):
        auth_context = AuthenticationContext(
            AzureTokenService.authority_url_format.format(self.__tenant_id))
        self.__token = auth_context.acquire_token_with_refresh_token(
            self.__token["refreshToken"], AzureTokenService.client_id,
            AzureTokenService.resource_url)
        self.__credentials = AADTokenCredentials(self.__token,
                                                 AzureTokenService.client_id)

        self.__update_refresh_token_timer()
def get_credentials(tenant_id, client_id, client_secret):
    authority_uri = '{0}/{1}'.format('https://login.microsoftonline.com',
                                     tenant_id)
    api_uri = 'https://management.core.windows.net'
    context = adal.AuthenticationContext(authority_uri, api_version=None)
    token = context.acquire_token_with_client_credentials(
        api_uri, client_id, client_secret)
    creds = AADTokenCredentials(token, client_id)
    if not creds:
        raise RuntimeError("Could not obtain credentials")
    return creds
Example #13
0
 def authenticate(self, tenant_id, scope):
     app = msal.ConfidentialClientApplication(self.client_id,
                                              authority=self.url +
                                              tenant_id,
                                              client_credential=self.secret)
     token = None
     token = app.acquire_token_silent(scope, account=None)
     if not token:
         logging.info(
             "No suitable token exists in cache. Retriving new one")
         token = app.acquire_token_for_client(scopes=scope)
         print(token)
     return AADTokenCredentials(token, self.client_id)
Example #14
0
    def _configure_post_auth(self):
        self.mgmtCredentials = AADTokenCredentials(
            self.mgmt_auth_token,
            cloud_environment=self.aad_environment_provider.
            getEnvironmentForId(self.aad_environment_id),
            tenant=self.aad_tenant_name)
        self.batchCredentials = AADTokenCredentials(
            self.batch_auth_token,
            cloud_environment=self.aad_environment_provider.
            getEnvironmentForId(self.aad_environment_id),
            tenant=self.aad_tenant_name)

        if self.can_init_from_config:
            self.init_from_config()
            self.ui.init_from_config()

        else:
            self.subscription_client = SubscriptionClient(
                self.mgmtCredentials,
                base_url=self.aad_environment_provider.getResourceManager(
                    self.aad_environment_id))
            self.ui.init_post_auth()
Example #15
0
def authenticate_client_key(authenticationInfo):
    """
    Authenticate using service principal w/ key.
    """
    authority_uri = authority_host_uri + '/' + authenticationInfo.tenant
    app_id = authenticationInfo.app_id
    app_secret = authenticationInfo.app_secret

    context = adal.AuthenticationContext(authority_uri, api_version=None)
    mgmt_token = context.acquire_token_with_client_credentials(resource_uri, app_id, app_secret)
    credentials = AADTokenCredentials(mgmt_token, app_id)

    return credentials
Example #16
0
    def authenticate_client_cert(self) -> ServicePrincipalCredentials:
        """
        Authenticate using service principal w/ cert.
        """
        authority_uri = FarmbeatsAuthHelper.AUTHORITY_HOST_URL + self.tenant_id
        context = adal.AuthenticationContext(authority_uri, api_version=None)

        mgmt_token = context.acquire_token_with_client_credentials(
            FarmbeatsAuthHelper.RESOURCE_HOST_URL, self.app_id,
            self.app_client_secret)

        credentials = AADTokenCredentials(mgmt_token, self.app_id)
        return credentials
def authenticate_client_key(tenant_id, client_id, client_secret):
    """
    Authenticate using service principal w/ key.
    """
    authority_host_uri = 'https://login.microsoftonline.com'
    authority_uri = authority_host_uri + '/' + tenant_id
    resource_uri = 'https://management.core.windows.net/'

    context = adal.AuthenticationContext(authority_uri, api_version=None)
    mgmt_token = context.acquire_token_with_client_credentials(
        resource_uri, client_id, client_secret)
    credentials = AADTokenCredentials(mgmt_token, client_id)

    return credentials
Example #18
0
def __get_credentials(creds: dict) -> ServicePrincipalCredentials:
    if creds['azure_client_secret'] is not None:
        credentials = ServicePrincipalCredentials(
            client_id=creds['azure_client_id'],
            secret=creds['azure_client_secret'],
            tenant=creds['azure_tenant_id'],
            cloud_environment=__get_cloud_env_by_name(creds['azure_cloud']))
    elif creds['access_token'] is not None:
        token = dict(accessToken=creds['access_token'])
        credentials = AADTokenCredentials(token, creds['azure_client_id'])
    else:
        raise InterruptExecution("Authentication to Azure requires a"
                                 " client secret or an access token")
    return credentials
Example #19
0
def renew_credentials(settings):
    context = adal.AuthenticationContext(settings['authority_uri'],
                                         api_version=None)
    code = context.acquire_user_code(settings['storage_account_uri'],
                                     settings['client_id'])
    print(code['message'])
    mgmt_token = context.acquire_token_with_device_code(
        settings['storage_account_uri'], code, settings['client_id'])
    credentials = AADTokenCredentials(mgmt_token, settings['client_id'])
    access_token = credentials.token['access_token']
    with open('account.txt', 'w') as at_out:
        at_out.write(access_token)

    return credentials
    def refresh_credential(self, credentials):
        """
        Refresh credentials
        """
        print_debug('Refreshing credentials')
        authority_uri = AUTHORITY_HOST_URI + '/' + self.get_tenant_id()
        existing_cache = self.context.cache
        context = adal.AuthenticationContext(authority_uri, cache=existing_cache)
        new_token = context.acquire_token(credentials.token['resource'],
                                          credentials.token['user_id'],
                                          credentials.token['_client_id'])

        new_credentials = AADTokenCredentials(new_token, credentials.token.get('_client_id'))
        return new_credentials
Example #21
0
def adb_authorization_client_key(params):
	"""
    Authenticate using service principal w/ key.
    """
	authority_host_uri = 'https://login.microsoftonline.com'
	tenant = params['tenant_id']
	authority_uri = authority_host_uri + '/' + tenant
	resource_uri = 'https://management.core.windows.net/'
	client_id = params['client_id']
	client_secret = params['client_secret']
	context = adal.AuthenticationContext(authority_uri, api_version=None)
	mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)
	credentials = AADTokenCredentials(mgmt_token, client_id)
	log.info("created management authorization token for databricks resource")
	return credentials
    def _create_client(credential, account_name) -> DataLakeStorageClient:
        scopes = "https://storage.azure.com/.default"
        token = credential.get_token(scopes)
        token_dict = token._asdict()
        token_dict['access_token'] = token_dict['token']
        aad_token_credentials = AADTokenCredentials(token_dict)

        dns_suffix = "dfs.core.windows.net"

        client = DataLakeStorageClient(aad_token_credentials,
                                       account_name,
                                       dns_suffix,
                                       x_ms_version=VERSION)
        client.config.base_url = 'https://{accountName}.{dnsSuffix}'
        return client
def get_adb_authorization_client_key(params):
	"""
    Authenticate using service principal w/ key.
    """
	authority_host_uri = AUTHORITY_HOST_URL
	tenant = params['tenant_id']
	authority_uri = authority_host_uri + '/' + tenant
	resource_uri = MANAGEMENT_HOST_URL
	client_id = params['client_id']
	client_secret = params['client_secret']
	context = adal.AuthenticationContext(authority_uri, api_version=None)
	mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)
	credentials = AADTokenCredentials(mgmt_token, client_id)
	log.info("created management authorization token for databricks resource")
	return credentials
def get_adb_authentication_client_key(params):
	"""
    Authenticate using service principal w/ key.
    """
	authority_host_uri = AUTHORITY_HOST_URL
	tenant = params['tenant_id']
	authority_uri = authority_host_uri + '/' + tenant
	resource_uri = DATABRICKS_RESOURCE_ID
	client_id = params['client_id']
	client_secret = params['client_secret']
	context = adal.AuthenticationContext(authority_uri, api_version=None)
	mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)
	credentials = AADTokenCredentials(mgmt_token, client_id)
	log.info("created aad authentication token")
	return credentials
def authenticate_device_code():

    authority_host_uri = 'https://login.microsoftonline.com'
    tenant = '45597f60-6e37-4be7-acfb-4c9e23b261ea' #SwissReTenantID
    authority_uri = authority_host_uri + '/' + tenant
    resource_uri = 'https://database.windows.net/'
    client_id = '04b07795-8ddb-461a-bbee-02f9e1bf7b46' # Global Client ID

    context = adal.AuthenticationContext(authority_uri, api_version=None)
    code = context.acquire_user_code(resource_uri, client_id)
    print(code['message'])
    mgmt_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
    credentials = AADTokenCredentials(mgmt_token, client_id)

    return credentials
def authenticate_client_key():
    """
    Authenticate using service principal w/ key.
    """
    authority_host_uri = '#'
    tenant = '#'
    authority_uri = authority_host_uri + '/' + tenant
    resource_uri = 'https://analysis.windows.net/powerbi/api'
    client_id = '#'
    client_secret = '#'

    context = adal.AuthenticationContext(authority_uri, api_version=None)
    mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)
    credentials = AADTokenCredentials(mgmt_token, client_id)

    return credentials
Example #27
0
    def __get_new_token(self):
        '''
        Acquires a new token using the clientID and secret.
        :return: newly generated token
        '''

        # generate token
        context = adal.AuthenticationContext(AUTHORITY_URI, api_version=None)
        mgmt_token = context.acquire_token_with_client_credentials(self.resource_uri, self.client_id, self.secret)
        credentials = AADTokenCredentials(mgmt_token, self.client_id)
        token = credentials.token["access_token"]

        # store new token
        self.token = token

        return self.token
Example #28
0
def authenticate_device_code(tenant_id):
    """
    Authenticate the end-user using device auth.
    """
    authority_host_uri = 'https://login.microsoftonline.com'
    authority_uri = authority_host_uri + '/' + tenant_id
    resource_uri = 'https://management.core.windows.net/'
    client_id = '04b07795-8ddb-461a-bbee-02f9e1bf7b46'

    context = adal.AuthenticationContext(authority_uri, api_version=None)
    code = context.acquire_user_code(resource_uri, client_id)
    print(code['message'])
    mgmt_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
    credentials = AADTokenCredentials(mgmt_token, client_id)

    return credentials
Example #29
0
async def authenticate_client_key(request):
    authority_host_uri = 'https://login.microsoftonline.com'
    authority_uri = authority_host_uri + '/' + TENANT

    context = adal.AuthenticationContext(authority_uri, api_version=None)
    mgmt_token = context.acquire_token_with_client_credentials(
        RESOURCE, CLIENT_ID, CLIENT_SECRET)
    credentials = AADTokenCredentials(mgmt_token, CLIENT_ID)
    token = credentials.token['access_token']
    uri = "https://graph.microsoft.com/beta/users?$filter=startsWith(userPrincipalName,'dron')&$select=UserPrincipalName"
    headers = {'Authorization': 'Bearer {}'.format(token)}
    r = requests.get(uri, headers=headers).json()
    users = r['value']
    return aiohttp_jinja2.render_template("azure-users.html",
                                          request,
                                          context={'users': users})
Example #30
0
def authenticate_device_code(code):
    """
    Authenticate the end-user using device auth.
    """
    authority_host_uri = 'https://login.microsoftonline.com'
    tenant = '----'
    authority_uri = authority_host_uri + '/' + tenant
    resource_uri = 'https://management.core.windows.net/'
    client_id = '------'

    context = adal.AuthenticationContext(authority_uri, api_version=None)
    code = context.acquire_user_code(resource_uri, client_id)
    mgmt_token = context.acquire_token_with_device_code(
        resource_uri, code, client_id)
    credentials = AADTokenCredentials(mgmt_token, client_id)

    return credentials