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)
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)
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 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
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)
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)
print(f"Ready: got tenant: {tenantId}") authority = f"https://login.microsoftonline.com/{tenantId}" clientID = '0cd93960-f119-4810-b13b-a25dffaef555' clientSecret = "" app = ConfidentialClientApplication(clientID, authority=authority, client_credential=clientSecret) scope = ["https://graph.microsoft.com/.default"] # The pattern to acquire a token looks like this. result = None # First, the code looks up a token from the cache. # Because we're looking for a token for the current app, not for a user, # use None for the account parameter. result = app.acquire_token_silent(scope, account=None) if not result: print("No suitable token exists in cache. Let's get a new one from AAD.") result = app.acquire_token_for_client(scopes=scope) if "access_token" in result: # Call a protected API with the access token. curToken = result["access_token"] print(curToken) endpoint = graphURI + "beta/conditionalAccess/policies" # endpoint = graphURI + "v1.0/users" http_headers = {'Authorization': 'Bearer ' + curToken, 'Accept': 'application/json', 'Content-Type': 'application/json'} data = requests.get(endpoint, headers=http_headers, stream=False).json()
except json.decoder.JSONDecodeError as error_description: print("An JSON error occured in the config file({0}): {1}".format( config_file, error_description)) quit() # Build authority from tanenat authority = "https://login.microsoftonline.com/{0}".format(config["tenant"]) # Setup the application with client id, client secret and tenant name app = ConfidentialClientApplication(config["client_id"], authority=authority, client_credential=config["client_secret"]) # Try to get token from memory cache, can be expanded to use a more # permanent storage like redis token_result = app.acquire_token_silent(config["scope"], account=None) if not token_result: # No token in cache, let's get a new one token_result = app.acquire_token_for_client(scopes=config["scope"]) # Check for token if "access_token" in token_result: # Make a request to the api print("Authed successfully") # --------------- Example 1a- Get a list of assets from Asset API --------------- print("Making call to Asset API to get list of assets") api_response = requests.get(config["assetApiEndpoint"] + "me/Assets", headers={