def __init__(self, config, client_id): self._config = config self._cache = token_cache.TokenCache() self._client_id = client_id if self._config.token_cache: self._cache.deserialize(self._config.token_cache) self._context = adal.AuthenticationContext(self._config.authority_url, cache=self._cache)
def _authentication_context_factory(tenant, cache): import adal authority_url = CLOUD.endpoints.active_directory is_adfs = authority_url.lower().endswith('/adfs') if not is_adfs: authority_url = authority_url + '/' + (tenant or _COMMON_TENANT) return adal.AuthenticationContext(authority_url, cache=cache, api_version=None, validate_authority=(not is_adfs))
def acquire_token(): authority_url = 'https://login.microsoftonline.com/{0}'.format( settings['tenant']) auth_ctx = adal.AuthenticationContext(authority_url) token = auth_ctx.acquire_token_with_username_password( 'https://graph.microsoft.com', settings['user_credentials']['username'], settings['user_credentials']['password'], settings['client_credentials']['client_id']) return token
def _getAzureADToken(self, aad_dict): if not aad_dict: return None # expecting argument to be dictionary with keys: AD_APP_ID, AD_TENANT_ID, AD_RESOURCE_ID app_id = aad_dict["AD_APP_ID"] tenant_id = aad_dict["AD_TENANT_ID"] resource_id = aad_dict["AD_RESOURCE_ID"] client_secret = None if "AD_CLIENT_SECRET" in aad_dict: client_secret = aad_dict["AD_CLIENT_SECRET"] token_cache_file = os.path.expanduser(f"~/.hsazcfg_{app_id}") if os.path.isfile(token_cache_file): # load this file and see if the token is expired or not mgmt_token = {} with open(token_cache_file, 'r') as f: mgmt_token = json.load(f) if "expiresOn" in mgmt_token and "accessToken" in mgmt_token: expiresOn = mgmt_token["expiresOn"] # expected format: "YYYY-MM-DD HH:MM:SS.163773" expire_dt = datetime.strptime(expiresOn, '%Y-%m-%d %H:%M:%S.%f') expire_ts = expire_dt.timestamp() if time.time() < expire_ts: # not expired yet! token = mgmt_token["accessToken"] return token # didn't get a token or it's expired, get new one authority_uri = MS_AUTHORITY_HOST_URI + '/' + tenant_id context = adal.AuthenticationContext(authority_uri, api_version=None) try: if client_secret: code = context.acquire_token_with_client_credentials( resource_id, app_id, client_secret) else: code = context.acquire_user_code(resource_id, app_id) except AdalError as ae: eprint(f"unable to process AD token: {ae}") return None access_token = None if "message" in code: eprint(code["message"]) mgmt_token = context.acquire_token_with_device_code( resource_id, code, app_id) if mgmt_token and "accessToken" in mgmt_token: with open(token_cache_file, 'w') as f: json.dump(mgmt_token, f) access_token = mgmt_token["accessToken"] elif "accessToken" in code: access_token = code["accessToken"] else: eprint("Could not authenticate with AD") return access_token
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
def acquire_token(): tenant_info = get_tenant_info(base_url) authority_url = 'https://login.microsoftonline.com/{0}'.format( tenant_info['name']) auth_ctx = adal.AuthenticationContext(authority_url) resource = tenant_info['base_url'] with open(cert_path, 'r') as file: key = file.read() json_token = auth_ctx.acquire_token_with_client_certificate( resource, client_id, key, thumbprint) return TokenResponse(**json_token)
def get_access_token_with_client_credentials(self, tenant_id, client_id, client_secret): context = adal.AuthenticationContext(self.LOGIN_ENDPOINT + '/' + tenant_id) token = context.acquire_token_with_client_credentials( resource=self.RESOURCE, client_id=client_id, client_secret=client_secret) return token
def _fresh_token(self): self.logger.debug('Fetching fresh authorization token.') ctx = adal.AuthenticationContext( 'https://login.microsoftonline.com/{}.onmicrosoft.com'.format( self.ms_config['tenant'])) self._token = ctx.acquire_token_with_client_certificate( self.site_url, self.ms_config['client_id'], self.ms_config['client_cert_key'], self.ms_config['client_cert'], )
def connect(self): context = adal.AuthenticationContext(const.PBI_AUTHORITY, validate_authority=True, api_version=None) token_response = context.acquire_token_with_username_password( const.PBI_RESOURCE, self._user_name, self._password, self._client_id) self._aad_token = token_response["accessToken"] self.is_connected = True
def get_token(): context = adal.AuthenticationContext( 'https://login.microsoftonline.com/TENANT.onmicrosoft.com') token_response = context.acquire_token_with_client_credentials( "https://management.azure.com/", "SERVICE_PRINCIPAL_NAME", "SERVICE_PRINCIPAL_PASSWORD") access_token = token_response.get('accessToken') print(access_token) return access_token
def test_api_version_default_value(self): with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") context = adal.AuthenticationContext( "https://login.windows.net/tenant") self.assertEqual(context._call_context['api_version'], '1.0') if len(caught_warnings) == 1: # It should be len(caught_warnings)==1, but somehow it works on # all my local test environment but not on Travis-CI. # So we relax this check, for now. self.assertIn("deprecated", str(caught_warnings[0].message))
def login(self, tenant, client, secret): context = adal.AuthenticationContext("%s/%s" % (self.AUTHORITY, tenant)) token = context.acquire_token_with_client_credentials( self.resource, client, secret) self._headers.update({ "Authorization": "Bearer %s" % token["accessToken"], "Content-Type": "application/json", })
def login(self, tenant, client, secret): context = adal.AuthenticationContext('%s/%s' % (self.AUTHORITY, tenant)) token = context.acquire_token_with_client_credentials( self.resource, client, secret) self._headers.update({ 'Authorization': 'Bearer %s' % token['accessToken'], 'Content-Type': 'application/json', })
def _authentication_context_factory(cli_ctx, tenant, cache): import re import adal authority_url = cli_ctx.cloud.endpoints.active_directory is_adfs = bool(re.match('.+(/adfs|/adfs/)$', authority_url, re.I)) if not is_adfs: authority_url = authority_url + '/' + (tenant or _COMMON_TENANT) return adal.AuthenticationContext(authority_url, cache=cache, api_version=None, validate_authority=(not is_adfs))
def refresh_token(self): logger.info("Refreshing token for Usage of MS-Graph") Authority_with_tenant = self.authority + self.tenant context = adal.AuthenticationContext(Authority_with_tenant) token = context.acquire_token_with_refresh_token( self.token['refreshToken'], self.client_id, self.resource, client_secret=None) logger.info("Token Refreshed successfully") return token
def get_token(): """Acquire token via client credential flow (ADAL Python library is utilized) """ authority_url = 'https://login.microsoftonline.com/{0}'.format( settings['tenant']) auth_ctx = adal.AuthenticationContext(authority_url) token = auth_ctx.acquire_token_with_client_credentials( "https://graph.microsoft.com", settings['client_credentials']['client_id'], settings['client_credentials']['client_secret']) return token
def GetToken(resource_url, client_id, username, password): authority_url = "https://login.microsoftonline.com/common" context = adal.AuthenticationContext(authority_url, validate_authority=True, api_version=None) token = context.acquire_token_with_username_password(resource=resource_url, username=username, password=password, client_id=client_id) access_token = token['accessToken'] return access_token
def refresh_access_token(): global access_token global refresh_token auth_context = adal.AuthenticationContext(AUTHORITY_URI) token = auth_context.acquire_token_with_refresh_token( refresh_token=refresh_token, client_id=CLIENT_ID, resource=RESOURCE_URI) access_token = token['accessToken'] refresh_token = token['refreshToken'] print("refresh_token ok")
def get_api_headers(): a_url = azure_key.objects.get(name="a_url").key client_secret = azure_key.objects.get(name="client_secret").key client_id = azure_key.objects.get(name="client_id").key context = adal.AuthenticationContext(a_url, api_version=None) token = context.acquire_token_with_client_credentials( client_id, client_id, client_secret) headers = { 'Authorization': "Bearer " + token['accessToken'], } return headers
def generate_oauth_token(self): context = adal.AuthenticationContext( str.format("https://login.microsoftonline.com/{}", self.settings.ACTIVE_DIRECTORY_TENANT_ID), api_version=None, validate_authority=True) token = context.acquire_token_with_client_credentials( "https://storage.azure.com", self.settings.ACTIVE_DIRECTORY_APPLICATION_ID, self.settings.ACTIVE_DIRECTORY_APPLICATION_SECRET) return token["accessToken"]
def test_acquire_token_with_user_pass_explicit(self): resource = '00000002-0000-0000-c000-000000000000' client_id_xplat = '04b07795-8ddb-461a-bbee-02f9e1bf7b46' authority = user_pass_params[ 'authorityHostUrl'] + '/' + user_pass_params['tenant'] context = adal.AuthenticationContext(authority) token_response = context.acquire_token_with_username_password( resource, user_pass_params['username'], user_pass_params['password'], client_id_xplat) self.validate_token_response_username_password(token_response)
def main_logic(): code = request.args['code'] state = request.args['state'] if state != session['state']: raise ValueError("State does not match") auth_context = adal.AuthenticationContext(AUTHORITY_URL) token_response = auth_context.acquire_token_with_authorization_code( code, REDIRECT_URI, config.RESOURCE, config.CLIENT_ID, config.CLIENT_SECRET) session['access_token'] = token_response['accessToken'] return redirect('/index')
def get_access_token(self, KeyVaultResourceName, AuthorizeUri, AADClientID, AADClientCertThumbprint, AADClientSecret): if not AADClientSecret and not AADClientCertThumbprint: raise Exception( "Neither AADClientSecret nor AADClientCertThumbprint were specified" ) if AADClientSecret and AADClientCertThumbprint: raise Exception( "Both AADClientSecret nor AADClientCertThumbprint were specified" ) if AADClientCertThumbprint: try: import adal except: raise Exception("adal library is not available on the VM") import waagent prv_path = os.path.join(waagent.LibDir, AADClientCertThumbprint.upper() + '.prv') prv_data = waagent.GetFileContents(prv_path) context = adal.AuthenticationContext(AuthorizeUri) result_json = context.acquire_token_with_client_certificate( KeyVaultResourceName, AADClientID, prv_data, AADClientCertThumbprint) access_token = result_json["accessToken"] return access_token token_uri = AuthorizeUri + "/oauth2/token" request_content = "resource=" + urllib.quote( KeyVaultResourceName ) + "&client_id=" + AADClientID + "&client_secret=" + urllib.quote( AADClientSecret) + "&grant_type=client_credentials" headers = {} http_util = HttpUtil(self.logger) result = http_util.Call(method='POST', http_uri=token_uri, data=request_content, headers=headers) self.logger.log("{0} {1}".format(result.status, result.getheaders())) result_content = result.read() if result.status != httplib.OK and result.status != httplib.ACCEPTED: self.logger.log(str(result_content)) return None http_util.connection.close() result_json = json.loads(result_content) access_token = result_json["access_token"] return access_token
def getAccessToken(self): AUTHORITY_URL = self.app.config.get( 'INTUNE_AUTHORITY_HOST_URL') + '/' + self.app.config.get( 'INTUNE_TENANT') auth_context = adal.AuthenticationContext(AUTHORITY_URL) token_response = auth_context.acquire_token_with_username_password( self.app.config.get('INTUNE_RESOURCE'), self.app.config.get('INTUNE_USER'), self.app.config.get('INTUNE_USER_PASS'), self.app.config.get('INTUNE_CLIENT_ID')) self.token = token_response['accessToken']
def get_credentials(self): authority_url = self.AUTH_ENDPOINT.format(self.tenant_id) context = adal.AuthenticationContext( authority_url, validate_authority=self.tenant_id != 'adfs', api_version=None, verify_ssl=False) try: return context.acquire_token_with_client_credentials( self.RESOURCE, self.client_id, self.client_secret) except Exception as e: raise self.__parse_error(e)
def token(self): authority_url = ('https://login.microsoftonline.com/' + self.settings['tenant']) RESOURCE = 'https://' + self.settings['web_api_resource'] context = adal.AuthenticationContext(authority_url) token = context.acquire_token_with_username_password( RESOURCE, self.settings['user'], self.settings['password'], self.settings['client_id']) return token
def __init__(self, auth_file): self.context = adal.AuthenticationContext(AUTHORITY_URI, api_version=None) self.auth_file = auth_file self.creds = self._read_creds() if self.creds and self.invalid: try: self.authenticate() self.creds = self._read_creds() except adal.adal_error.AdalError as err: log.error("Failed to refresh tokens: %s", str(err)) self.creds = None
def __init__(self, root: str, hostname: str, resource: str, client_id: str, secret: str, tenant: str, **kwargs) -> None: super().__init__(kwargs.get('http_config', {})) self._root = root # type: str self._hostname = hostname # type: str self._resource = resource # type: str self._client_id = client_id # type: str self._client_secret = secret # type: str self._auth_context = adal.AuthenticationContext( 'https://login.windows.net/' + tenant) self.http_client = CdmHttpClient() # type: CdmHttpClient
def ShowCampaign(id): campaignId=id resource_url = 'https://analysis.windows.net/powerbi/api' #username='******' #password='******' PbiUserID = str(os.environ['PbiUserID']) PbiPassword = str(os.environ['PbiPassword']) print("-------------------------") print("PBIUserId="+PbiUserID) print("PbiPassword="******"-------------------------") print(current_user) #profession=Profession.query.all() client_id='4e4bf593-32b5-4d99-a860-bb26cdb0e2f7' AuthContext= adal.AuthenticationContext("https://login.windows.net/common") token=AuthContext.acquire_token_with_username_password(resource_url,PbiUserID,PbiPassword,client_id) accessToken=token["accessToken"] url="https://api.powerbi.com/v1.0/myorg/groups/42b9d168-fefb-4b3c-aa2d-af24fb08f4d8/reports" headers = {'Authorization': 'Bearer ' + accessToken,'Content-type': 'application/json', 'Accept': 'application/json'} response=requests.get(url, headers=headers) reportId=response.json()["value"][0]['id'] reportUrl=response.json()["value"][0]["webUrl"]+"/GenerateToken" print(response.json()) #reportUrl="https://api.powerbi.com/v1.0/myorg/reports/"+response.json()["value"][0]['id']+"/GenerateToken" reportId="f01e98f3-abb9-4f51-bca3-a9eb419ee97e" reportId="187ffc03-1c8e-4cb8-a19c-d182c2b01b16" reportId="07ca665c-974a-4eca-a85e-64ba41c98a2b" reportUrl="https://api.powerbi.com/v1.0/myorg/groups/42b9d168-fefb-4b3c-aa2d-af24fb08f4d8/reports/"+reportId+"/GenerateToken" data1= { 'allowSaveAs' : 'false', "accessLevel" : "view", "identities" : [ { "username":campaignId, "roles":["Campaign"], "datasets":["165a34d6-42a9-49fc-b6d4-50be5bac0f40"] } ] } responseEmbedToken=requests.post(reportUrl,data=json.dumps(data1),headers=headers) print(responseEmbedToken.text) embedurl="https://app.powerbi.com/reportEmbed?reportId="+reportId+"&groupId=42b9d168-fefb-4b3c-aa2d-af24fb08f4d8" configObj={'token':responseEmbedToken.json()["token"],'embedurl':embedurl,'reportid':reportId} professions=Profession.query.all() specialtyGroups=SpecialtyGroup.query.all() geoRegions=GeoRegions.query.all() Segments=Segment.query.all() customerName=Customer.query.get(current_user.customerid).name return render_template('dashboard/Pbi.html',customer_name=customerName,segments=Segments,professions=professions,specialtyGroups=specialtyGroups,geoRegions=geoRegions,configObj=json.dumps(configObj))
def acquire_token(): global access_token global refresh_token auth_context = adal.AuthenticationContext(AUTHORITY_URI) token = auth_context.acquire_token_with_username_password( resource=RESOURCE_URI, client_id=CLIENT_ID, username=USER_ACCOUNT, password=USER_PASSWORD) access_token = token['accessToken'] refresh_token = token['refreshToken'] print("acuqire_token ok")