class ApplicationKeyTokenProvider(TokenProviderBase): """ Acquire a token from MSAL with application Id and Key """ def __init__(self, kusto_uri: str, authority_uri: str, app_client_id: str, app_key: str): super().__init__(kusto_uri) self._msal_client = None self._app_client_id = app_client_id self._app_key = app_key self._auth = authority_uri @staticmethod def name() -> str: return "ApplicationKeyTokenProvider" def context(self) -> dict: return {"authority": self._auth, "client_id": self._app_client_id} def _init_impl(self): self._msal_client = ConfidentialClientApplication(client_id=self._app_client_id, client_credential=self._app_key, authority=self._auth) def _get_token_impl(self) -> dict: token = self._msal_client.acquire_token_for_client(scopes=self._scopes) return self._valid_token_or_throw(token) def _get_token_from_cache_impl(self) -> dict: token = self._msal_client.acquire_token_silent(scopes=self._scopes, account=None) return self._valid_token_or_none(token)
class ApplicationCertificateTokenProvider(TokenProviderBase): """ Acquire a token from MSAL using application certificate Passing the public certificate is optional and will result in Subject Name & Issuer Authentication """ def __init__(self, kusto_uri: str, client_id: str, authority_uri: str, private_cert: str, thumbprint: str, public_cert: str = None): super().__init__(kusto_uri) self._msal_client = None self._auth = authority_uri self._client_id = client_id self._cert_credentials = {TokenConstants.MSAL_PRIVATE_CERT: private_cert, TokenConstants.MSAL_THUMBPRINT: thumbprint} if public_cert is not None: self._cert_credentials[TokenConstants.MSAL_PUBLIC_CERT] = public_cert @staticmethod def name() -> str: return "ApplicationCertificateTokenProvider" def context(self) -> dict: return {"authority": self._auth, "client_id": self._app_client_id, "thumbprint": self._cert_credentials[TokenConstants.MSAL_THUMBPRINT]} def _init_impl(self): self._msal_client = ConfidentialClientApplication(client_id=self._client_id, client_credential=self._cert_credentials, authority=self._auth) def _get_token_impl(self) -> dict: token = self._msal_client.acquire_token_for_client(scopes=self._scopes) return self._valid_token_or_throw(token) def _get_token_from_cache_impl(self) -> dict: token = self._msal_client.acquire_token_silent(scopes=self._scopes, account=None) return self._valid_token_or_none(token)
def _get_azure_ad_access_token(self) -> str: """ https://msal-python.readthedocs.io/en/latest/#msal.ConfidentialClientApplication """ app = ConfidentialClientApplication( client_id=self.oauth_client_id, client_credential=self.oauth_client_secret, authority=self.oauth_client_authority) result = None config = { "scope": ["https://graph.microsoft.com/.default"], } if not result: result = app.acquire_token_for_client(scopes=config["scope"]) if "access_token" not in result: print(result.get("error")) print(result.get("error_description")) print(result.get( "correlation_id")) # You might need this when reporting a bug. raise dbt.exceptions.FailedToConnectException( 'failed to connect to Azure') # print("ACCESS TOKEN:"+ result["access_token"]) # return result["access_token"] return "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyIsImtpZCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyJ9.eyJhdWQiOiIyZmY4MTRhNi0zMzA0LTRhYjgtODVjYi1jZDBlNmY4NzljMWQiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8yY2M0ZjZiZS1kMjMzLTQ5NjgtYTkyYy03NGNlMmQyNmFkYjEvIiwiaWF0IjoxNjEzOTEzNTk2LCJuYmYiOjE2MTM5MTM1OTYsImV4cCI6MTYxMzkxNzQ5NiwiYWNyIjoiMSIsImFpbyI6IkFVUUF1LzhUQUFBQWtlbWNtcGpGdEw2NzNEakJPOWtpdHg2eFZiTDVRalNqTExLaGtJa2hMUUE1Q3c0WVNIb0haWG5nc0FGbVdLeDJaV2JucTZkWFc1M2dhZnZRMnhxS2NnPT0iLCJhbHRzZWNpZCI6IjE6bGl2ZS5jb206MDAwM0JGRkQxM0FBQkU3RiIsImFtciI6WyJwd2QiXSwiYXBwaWQiOiI0NTRjZjY3OS1jOGMzLTQ0OTUtOTllMy1jZWMzMjAxNDU4MDkiLCJhcHBpZGFjciI6IjAiLCJlbWFpbCI6InZhbGRhc0BtYWtzaW1hdmljaXVzLmV1IiwiZmFtaWx5X25hbWUiOiIyZGRhMWYzYS0zMjExLTRjMjAtYTdjMC1jYzliMmY3ZmI4NzkiLCJnaXZlbl9uYW1lIjoiZjk1ZWQ5NzgtY2I0My00OThjLWIxNmUtMTU0MGQ5NWYzNDQxIiwiaWRwIjoibGl2ZS5jb20iLCJpcGFkZHIiOiI3OC41OC4yMzcuMTY2IiwibmFtZSI6ImY5NWVkOTc4LWNiNDMtNDk4Yy1iMTZlLTE1NDBkOTVmMzQ0MSAyZGRhMWYzYS0zMjExLTRjMjAtYTdjMC1jYzliMmY3ZmI4NzkiLCJvaWQiOiIwYjRmNWQ3OC03ZTBlLTQyMzItYmI2MS01NjNmZmVlNDlhNzQiLCJwdWlkIjoiMTAwMzAwMDBBQzAwN0U3NyIsInJoIjoiMC5BVEVBdnZiRUxEUFNhRW1wTEhUT0xTYXRzWG4yVEVYRHlKVkVtZVBPd3lBVVdBa3hBSm8uIiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwic3ViIjoiVGNpaS16bXhDUTkxSjdCWVoxdGpKdkVSb0xLQ0FGQ2NPeGYtYmo3QzF3SSIsInRpZCI6IjJjYzRmNmJlLWQyMzMtNDk2OC1hOTJjLTc0Y2UyZDI2YWRiMSIsInVuaXF1ZV9uYW1lIjoibGl2ZS5jb20jdmFsZGFzQG1ha3NpbWF2aWNpdXMuZXUiLCJ1dGkiOiJNZ1JhczNXUVUwQ3R0d0I3cUVCQkFBIiwidmVyIjoiMS4wIn0.PGjS4bHZTMCFQnbBNUUg1w5G9YTem1dfjM3eiBf1-sVPRRyRyUlB28nB7PjYB_GnR235ZmaBkc3TF0mToGUqC43Zky2a0CWlAEmRyzUH85y8RIWzgnEx5cRi7SC46klzqHa78xnQWoihjPCG23VT8bo3nwKH0JziH6DFBmsrFc0wwqMBm4l_xjf_3MgPr5Fk-GzQ_LtryUvxdiATXAjqiK6Zcmm1fPKZZAdizP4EQImfGALbDwjoIdyggyInnZzOGWJjODXPaFMpbNnKM8LWGcpMgNfCeShfWchOSn5JqNvVBMIrsRkuVzo8eDOK_e63YTASncj4ncNRJ4EDtlBQGA"
def __init__(self, spn_tenant_id: str, spn_client_id: str, spn_client_secret: str): app_client = ConfidentialClientApplication( client_id=spn_client_id, authority=f"https://login.microsoftonline.com/{spn_tenant_id}", client_credential=spn_client_secret ) token = app_client.acquire_token_for_client(scopes="https://cloudpartner.azure.com/.default") if 'error' in token: raise RuntimeError("Could not fetch token for Azure Marketplace client", token['error_description']) self.token = token['access_token']
def fetch_from_sharepoint_list(table_name: str, sub_site_id: str, list_id: str, **kwargs): s3 = S3Data(table_name, kwargs["ts_nodash"]) app = ConfidentialClientApplication( DIT_SHAREPOINT_CREDENTIALS['client_id'], authority= f'https://login.microsoftonline.com/{DIT_SHAREPOINT_CREDENTIALS["tenant_id"]}', client_credential=DIT_SHAREPOINT_CREDENTIALS['client_secret'], ) token_response = app.acquire_token_for_client( scopes=['https://graph.microsoft.com/.default']) if 'access_token' not in token_response: raise InvalidAuthCredentialsError( f'Failed to acquire token: {token_response.get("error_description")}' ) access_token = token_response['access_token'] tenant = DIT_SHAREPOINT_CREDENTIALS["tenant_domain"] sharepoint_site = ( f':/sites/{DIT_SHAREPOINT_CREDENTIALS["site_name"]}:/sites/{sub_site_id}' ) list_url = f'https://graph.microsoft.com/v1.0/sites/{tenant}{sharepoint_site}/lists/{list_id}' items_url = f'{list_url}/items' # Fetch a copy of the column names, this needs to be done separately from # fetching items as otherwise paging will not work. logger.info('Fetching column names from %s', list_url) graph_data = _make_request(list_url, access_token, {'expand': 'columns'}) column_map = { col['name']: col['displayName'] for col in graph_data['columns'] } # Fetch the list item data page = 1 while items_url is not None: logger.info('Fetching from %s', items_url) graph_data = _make_request(items_url, access_token, {'expand': 'fields'}) records = [{ **{ column_map[col_id]: row['fields'][col_id] for col_id in row['fields'].keys() if col_id in column_map }, 'createdBy': row['createdBy']['user'], 'lastModifiedBy': row['lastModifiedBy']['user'] if row.get('lastModifiedBy') is not None else None, } for row in graph_data['value']] s3.write_key(f"{page:010}.json", records) page += 1 items_url = graph_data.get('@odata.nextLink') logger.info('Finished fetching from sharepoint')
def ms_graph_client_token(): azure_tenant_id = os.environ["AZURE_TENANT_ID"] client_id = os.environ["MS_GRAPH_API_CLIENT_ID"] client_secret = os.environ["MS_GRAPH_API_CLIENT_SECRET"] context = ConfidentialClientApplication( client_id=client_id, client_credential=client_secret, authority="https://login.microsoftonline.com/{}".format( azure_tenant_id), ) scope = "https://graph.microsoft.com/.default" return context.acquire_token_for_client(scope)
def __init__(self, spn_tenant_id: str, spn_client_id: str, spn_client_secret: str): app_client = ConfidentialClientApplication( spn_client_id, authority=f"https://login.microsoftonline.com/{spn_tenant_id}", client_credential=spn_client_secret) token = app_client.acquire_token_for_client( scopes="https://cloudpartner.azure.com/.default") self.req_headers = { "Authorization": f"Bearer {token['access_token']}", "Content-Type": "application/json", } self.req_params = {"api-version": "2017-10-31"}
async def get_user(self, auth_token: ExternalAuthToken) -> ExternalUser: # Get Azure's endpoints from discovery document discovery_document = await self._get_discovery_document() try: token_endpoint = discovery_document["token_endpoint"] userinfo_endpoint = discovery_document["userinfo_endpoint"] except KeyError as exc: raise DiscoveryDocumentError(f"Could not parse Azure's discovery document: {repr(exc)}") msal_client = ConfidentialClientApplication( config.AZURE_CLIENT_ID, authority=config.AZURE_AUTHORITY, client_credential=config.AZURE_CLIENT_SECRET ) # Request access_token from Azure try: result = msal_client.acquire_token_by_authorization_code( auth_token.code, redirect_uri=config.AZURE_REDIRECT_URL, scopes=["User.Read"], ) access_token = result['access_token'] except Exception as exc: raise ProviderConnectionError(f"Could not get Azure's access token: {repr(exc)}") # Request user's information from Azure userinfo_response = requests.get( # Currently userinfo_endpoint only returns "sub". We need to use /v1.0/users for other info "https://graph.microsoft.com/v1.0/users", headers={'Authorization': 'Bearer ' + access_token} ) if userinfo_response.json().get("value"): email = result["id_token_claims"]["email"] sub_id = result["id_token_claims"]["sub"] username = None if userinfo_response.json()["value"]: username = userinfo_response.json()["value"][0].get("givenName") else: raise UnauthorizedUser("User account not verified by Azure.") external_user = ExternalUser( email=email, username=username, external_sub_id=sub_id ) return external_user
async def get_request_uri(self) -> str: msal_client = ConfidentialClientApplication( config.AZURE_CLIENT_ID, authority=config.AZURE_AUTHORITY, client_credential=config.AZURE_CLIENT_SECRET) state_csrf_token = await create_state_csrf_token() request_uri = msal_client.get_authorization_request_url( scopes=["User.Read"], state=state_csrf_token, redirect_uri=config.AZURE_REDIRECT_URL) return request_uri, state_csrf_token
def __init__(self, config: Dict): client_id: str = config['GRAPH_API_AUTH_CLIENT_ID'] authority: str = config['GRAPH_API_AUTH_AUTHORITY'] thumprint: str = config['GRAPH_API_AUTH_PUBKEY_THUMBPRINT'] priv_key_path: str = config['GRAPH_API_AUTH_PRIVKEY_PATH'] client_credential: dict = { "thumbprint": thumprint, "private_key": open(priv_key_path).read() } self.app = ConfidentialClientApplication( client_id=client_id, authority=authority, client_credential=client_credential)
def auth_sign_in(): session["state"] = str(uuid4()) auth_client = ConfidentialClientApplication( app.config["AUTH_CLIENT_ID"], authority=current_app.config["AUTH_CLIENT_TENANCY"], client_credential=app.config["AUTH_CLIENT_SECRET"], ) auth_code_flow = auth_client.initiate_auth_code_flow( scopes=current_app.config["AUTH_CLIENT_SCOPES"], state=session.get("state"), redirect_uri="http://localhost:5000/auth/callback", ) session["auth_code_flow"] = auth_code_flow auth_uri = auth_code_flow.get("auth_uri") return f'<a href="{auth_uri}">Click to Login</a>.'
def __get_msal_app(self): if not self.app: self.app = ConfidentialClientApplication( client_id=self.microsoft_app_id, client_credential=self.microsoft_app_password, authority=self.oauth_endpoint, ) return self.app
def generatetoken(): with open('app/json_files/credential.json') as f: credentials = json.load(f) appMS = ConfidentialClientApplication( credentials.get('CLIENT_ID', {}), authority=credentials.get('AUTHORITY', {}), client_credential=credentials.get('CLIENT_SECRET', {})) result = None scope = credentials.get('SCOPE', {}) result = appMS.acquire_token_silent(scopes=list(scope), account=None) if not result: logging.info( "No suitable token exists in cache. Let's get a new one from AAD.") result = appMS.acquire_token_for_client(scopes=scope) token = result.get('access_token', {}) return token
def _get_msgraph_token() -> str: scopes = ["https://graph.microsoft.com/.default"] app = ConfidentialClientApplication( client_id=config.API_CLIENT_ID, client_credential=config.API_CLIENT_SECRET, authority=f"{config.AAD_INSTANCE}/{config.AAD_TENANT_ID}") result = app.acquire_token_silent(scopes=scopes, account=None) if not result: logging.info( 'No suitable token exists in cache, getting a new one from AAD' ) result = app.acquire_token_for_client(scopes=scopes) if "access_token" not in result: logging.debug(result.get('error')) logging.debug(result.get('error_description')) logging.debug(result.get('correlation_id')) raise Exception(result.get('error')) return result["access_token"]
def create(cls, **kwargs) -> ConfidentialClientApplication: client_id = kwargs["client_id"] client_secret = kwargs["client_secret"] authority = kwargs["authority"] return ConfidentialClientApplication( client_id, client_secret, authority)
def patching_oms(plugin, date): AZURE_TENANT = plugin.params.get(name="AZURE_TENANT").value AZURE_APP_ID = plugin.params.get(name="AZURE_APP_ID").value AZURE_APP_SECRET = plugin.params.get(name="AZURE_APP_SECRET").value AZURE_LOG_WORKSPACE = plugin.params.get(name="AZURE_LOG_WORKSPACE").value LOG_ANALYTICS_BASE = "https://api.loganalytics.io" LOG_ANALYTICS_BASE_SCOPE = "{}/.default".format(LOG_ANALYTICS_BASE) LOG_ANALYTICS_QUERY = "{}/v1/workspaces/{}/query".format( LOG_ANALYTICS_BASE, AZURE_LOG_WORKSPACE) ctx = ConfidentialClientApplication( client_id=AZURE_APP_ID, client_credential=AZURE_APP_SECRET, authority=AZURE_TENANT, ) token = ctx.acquire_token_for_client(LOG_ANALYTICS_BASE_SCOPE) headers = {"Authorization": "Bearer {}".format(token["access_token"])} patching = requests.get( LOG_ANALYTICS_QUERY, params={ "query": "(ConfigurationData | project Computer, TimeGenerated, VMUUID | distinct Computer) | join kind=inner ( Heartbeat | project Computer, OSType, OSName, OSMajorVersion, OSMinorVersion, ComputerEnvironment, TimeGenerated, TenantId, ComputerIP | summarize arg_max (TimeGenerated, *) by Computer ) on Computer" }, headers=headers, ) results = patching.json() for computer in results["tables"][0]["rows"]: host_status = lookup(computer[0], date) if host_status is None: continue host_status.patching_info = { "id": computer[8], "os_type": computer[3], "os_name": computer[4], "os_major_version": computer[5], "os_minor_version": computer[6], } host_status.patching_plugin = plugin host_status.patching_output = "Server has been enrolled in OMS." host_status.patching_status = 3 host_status.save() print("Updated patching status for {}".format(host_status))
def get_sp_access_token(client_id,client_credential,tenant_name,scopes): logging.info('Attempting to obtain an access token...') result = None app = ConfidentialClientApplication( client_id = client_id, client_credential= client_credential, authority = f"https://login.microsoftonline.com/{tenant_name}" ) result = app.acquire_token_for_client(scopes=scopes) if "access_token" in result: logging.info('Access token successfully acquired') return result['access_token'] else: logging.error('Unable to obtain access token') logging.error(f"Error was: {result['error']}") logging.error(f"Error description was: {result['error_description']}") logging.error(f"Error correlation_id was: {result['correlation_id']}") raise Exception('Failed to obtain access token')
def teams_session(): client_id = ge('client_id') authority_id = ge('authority_id') client_credential = ge('client_credential') BASE_URL = "https://graph.microsoft.com/beta/" ms_s = sessions.BaseUrlSession(base_url=BASE_URL) app = ConfidentialClientApplication( client_id=client_id, authority=f"https://login.microsoftonline.com/{authority_id}", client_credential=client_credential) result = app.acquire_token_for_client( scopes=["https://graph.microsoft.com/.default"]) token = result['access_token'] sessions.BaseUrlSession(base_url='https://graph.microsoft.com/beta/') ms_s.headers.update({"Authorization": f"Bearer {token}"}) return ms_s
def auth_sign_in(): session["state"] = str(uuid4()) auth_url = ConfidentialClientApplication( app.config["AUTH_CLIENT_ID"], authority=current_app.config["AUTH_CLIENT_TENANCY"], client_credential=app.config["AUTH_CLIENT_SECRET"], ).get_authorization_request_url( scopes=current_app.config["AUTH_CLIENT_SCOPES"], state=session.get("state"), redirect_uri="http://localhost:9000/auth/callback", ) return f'<a href="{auth_url}">Click to Login</a>.'
def __get_msal_app(self): if not self.app: self.app = ConfidentialClientApplication( client_id=self.microsoft_app_id, authority=self.oauth_endpoint, client_credential={ "thumbprint": self.certificate_thumbprint, "private_key": self.certificate_private_key, }, ) return self.app
async def __get_confidential_client_application( form: ClientCredentialsForm) -> ConfidentialClientApplication: """Get a confidential client application. :param form: Client form :return: Confidential client application """ return ConfidentialClientApplication( client_id=form.client_id, client_credential=form.client_secret.get_secret_value(), authority=os.getenv("AZURE_AD_AUTHORITY"), )
class Authenticator: app: ConfidentialClientApplication def __init__(self, config: Dict): client_id: str = config['GRAPH_API_AUTH_CLIENT_ID'] authority: str = config['GRAPH_API_AUTH_AUTHORITY'] thumprint: str = config['GRAPH_API_AUTH_PUBKEY_THUMBPRINT'] priv_key_path: str = config['GRAPH_API_AUTH_PRIVKEY_PATH'] client_credential: dict = { "thumbprint": thumprint, "private_key": open(priv_key_path).read() } self.app = ConfidentialClientApplication( client_id=client_id, authority=authority, client_credential=client_credential) def get_auth_token(self) -> str: """ Returns a valid auth_token or throws a value exception """ result = None # Check in cache result = self.app.acquire_token_silent(AUTHENTICATION_SCOPE, account=None) if not result: print("Getting new token") result = self.app.acquire_token_for_client( scopes=AUTHENTICATION_SCOPE) if "access_token" in result: return result["access_token"] print(result.get("error")) print(result.get("error_description")) # You may need this when reporting a bug print(result.get("correlation_id")) raise ValueError(result)
def _client_factory(self, token_cache: SerializableTokenCache = None, b2c_policy: str = None, **msal_client_kwargs) -> ConfidentialClientApplication: client_config = self.aad_config.client.__dict__.copy( ) # need to make a copy since contents must be mutated client_config[ 'authority'] = f'{self.aad_config.client.authority}{b2c_policy or ""}' if token_cache: client_config['token_cache'] = token_cache client_config.update(**msal_client_kwargs) return ConfidentialClientApplication(**client_config)
class ApplicationKeyTokenProvider(CloudInfoTokenProvider): """Acquire a token from MSAL with application Id and Key""" def __init__(self, kusto_uri: str, authority_id: str, app_client_id: str, app_key: str, is_async: bool = False): super().__init__(kusto_uri, is_async) self._msal_client = None self._app_client_id = app_client_id self._app_key = app_key self._auth = authority_id @staticmethod def name() -> str: return "ApplicationKeyTokenProvider" def _context_impl(self) -> dict: return { "authority": self._cloud_info.authority_uri(self._auth), "client_id": self._app_client_id } def _init_impl(self): self._msal_client = ConfidentialClientApplication( client_id=self._app_client_id, client_credential=self._app_key, authority=self._cloud_info.authority_uri(self._auth), proxies=self._proxy_dict) def _get_token_impl(self) -> Optional[dict]: token = self._msal_client.acquire_token_for_client(scopes=self._scopes) return self._valid_token_or_throw(token) def _get_token_from_cache_impl(self) -> dict: token = self._msal_client.acquire_token_silent(scopes=self._scopes, account=None) return self._valid_token_or_none(token)
def __init__( self, client_config: MSALClientConfig, cache: Optional[SerializableTokenCache] = None, ): self.client_config = client_config self._cca = ConfidentialClientApplication( client_id=client_config.client_id, client_credential=client_config.client_credential, authority=client_config.authority, app_name=client_config.app_name, app_version=client_config.app_version, token_cache=cache, )
def auth_callback(): if request.args.get("state") != session.get("state"): return "Sign-in failed, state doesn't match.", 403 if request.args.get("error"): return request.args.get("error"), 403 if not request.args.get("code"): return "Sign-in failed, no auth code.", 403 result = ConfidentialClientApplication( app.config["AUTH_CLIENT_ID"], authority=current_app.config["AUTH_CLIENT_TENANCY"], client_credential=app.config["AUTH_CLIENT_SECRET"], ).acquire_token_by_authorization_code( code=request.args.get("code"), scopes=current_app.config["AUTH_CLIENT_SCOPES"], redirect_uri="http://localhost:9000/auth/callback", ) if result.get("error"): return "Sign-in failed.", 403 if not result.get("access_token"): return "Sign-in failed, no access token.", 403 session["access_token"] = result.get("access_token") return "Signed-in"
def main(tenant_id, client_id, client_secret): authority = "https://login.microsoftonline.com/{tenant_id}".format( tenant_id=tenant_id) app = ConfidentialClientApplication(client_id=client_id, authority=authority, client_credential=client_secret) token_response = app.acquire_token_for_client( ["https://graph.microsoft.com/.default"]) print("Response: ", token_response) print("Access token: ", token_response['access_token']) api_endpoint = "https://management.azure.com/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions?api-version=2019-09-01" # The tenant id is the root management group api_endpoint = api_endpoint.format(managementGroupId=tenant_id) session = request_authenticated_azure_session( token_response['access_token']) with session as req: response = req.get(api_endpoint) if response.status_code in range(200, 299): print(response.json()) else: print("Oops!")
async def get_obo_token( auth_settings: AuthSettings = Depends(get_auth_settings), msal_app: msal.ConfidentialClientApplication = Depends( get_private_app), ): tenant = urlparse(auth_settings.b2c_endpoint).path.lstrip('/') scopes = [ f'https://{tenant}/{auth_settings.elastic_client_id}/.default', ] token_resp = msal_app.acquire_token_for_client(scopes) try: return token_resp['access_token'] except KeyError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Unable to acquire elastic access token', headers={'WWW-Authenticate': 'Bearer'}, )
def __init__(self, server_address, handler_class=TopologyHandler): super().__init__(server_address, handler_class) tenant_id, client_id, client_secret = get_azure_account_info() # Authority authority = "https://login.microsoftonline.com/" + tenant_id # Retrieve the list of Workspace IDs, separated by comma workspace_ids = os.environ.get("AZURE_LOG_ANALYTICS_WORKSPACES") if not workspace_ids: raise ValueError('You must define AZURE_LOG_ANALYTICS_WORKSPACES environment ' 'variable to specify a list of workspace IDs separated by comma.') self.app = ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret) self.scope = [resource_id] self.workspaces = str(workspace_ids).split(",") client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self.serializer = Serializer(client_models) self.deserializer = Deserializer(client_models)
def getConfidentialClientAccessToken(self) -> Optional[str]: # Initialise the app if not already exist if not self.app: logging.info("Initialise msal connection app") self.app = ConfidentialClientApplication( client_id=self.app_id, authority=self.authority, client_credential=self.app_secret) # try to get the token from cache if already exist result = self.app.acquire_token_silent(scopes=self.scopes, account=None) if not result: logging.info( "No suitable token exists in cache. Let's get a new one from AAD." ) result = self.app.acquire_token_for_client(scopes=self.scopes) if "access_token" in result: return result["access_token"] return None