def get_access_token(self): """ Get the access token for this Azure Service Principal :return access_token: """ app = msal.ConfidentialClientApplication( self.AZURE_CLIENT_ID, authority= f"https://login.microsoftonline.com/{self.AZURE_TENANT_ID}", client_credential=self.AZURE_CLIENT_SECRET, ) # Lookup the token in cache result = app.acquire_token_silent(self.AZURE_APP_SCOPE, account=None) if not result: logging.info( "No suitable token exists in cache. Let's get a new one from AAD." ) result = app.acquire_token_for_client(scopes=self.AZURE_APP_SCOPE) if "access_token" in result: # print("Successfully authenticated!") return result["access_token"] else: print(result.get("error")) print(result.get("error_description")) print(result.get( "correlation_id")) # You may need this when reporting a bug
def test_windows_token_cache_roundtrip(): client_id = os.getenv('AZURE_CLIENT_ID') client_secret = os.getenv('AZURE_CLIENT_SECRET') if not (client_id and client_secret): pytest.skip( 'no credentials present to test WindowsTokenCache round-trip with.' ) test_folder = tempfile.mkdtemp( prefix="msal_extension_test_windows_token_cache_roundtrip") cache_file = os.path.join(test_folder, 'msal.cache') try: subject = WindowsTokenCache(cache_location=cache_file) app = msal.ConfidentialClientApplication( client_id=client_id, client_credential=client_secret, token_cache=subject) desired_scopes = ['https://graph.microsoft.com/.default'] token1 = app.acquire_token_for_client(scopes=desired_scopes) os.utime(cache_file, None) # Mock having another process update the cache. token2 = app.acquire_token_silent(scopes=desired_scopes, account=None) assert token1['access_token'] == token2['access_token'] finally: shutil.rmtree(test_folder, ignore_errors=True)
def get_access_token(config): """ Get access token from cache or a new one """ target_credentials = config.target_credentials client_id = target_credentials["client_id"] client_secret = target_credentials["client_secret"] authority_url = target_credentials["authority"] tenant_id = target_credentials["tenant_id"] scopes = target_credentials["scopes"] # Load access token from cache file token_cache = load_token_cache() auth_app = msal.ConfidentialClientApplication( client_id=client_id, client_credential=client_secret, authority=f"{authority_url}/{tenant_id}", token_cache=token_cache) # Try to get a token from cache response = auth_app.acquire_token_silent(scopes, account=None) # No cached token found. Create a new one if not response: response = auth_app.acquire_token_for_client(scopes) # Save token to cache file if modified save_token_cache(token_cache) return response['access_token']
async def get_token(): client_id = "d7b889ea-d93d-48bf-8589-196c00c48421" client_secret = "" # Create a preferably long-lived app instance which maintains a token cache. app = msal.ConfidentialClientApplication( client_id, authority=config["authority"], client_credential=client_secret, # token_cache=... # Default cache is in memory only. # You can learn how to use SerializableTokenCache from # https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache ) # The pattern to acquire a token looks like this. result = None # Since we are looking for token for the current app, NOT for an end user, # notice we give account parameter as None. result = app.acquire_token_silent(config["scope"], account=None) if not result: logging.info("No token exists in cache. Getting a new one from AzureAD.") result = app.acquire_token_for_client(scopes=config["scope"]) result["renew_datetime"] = datetime.datetime.now() + datetime.timedelta(seconds=result["expires_in"]) return result
def _build_context(self): """Build context when users make the first call. Also need to ensure client Id, tenant and secret are not null.""" if self._auth_context is None: self._auth_context = msal.ConfidentialClientApplication( self.client_id, authority=self.endpoint.value + self.tenant, client_credential=self.secret)
def _build_msal_app(cache=None, authority=None): # return None return msal.ConfidentialClientApplication( Config.CLIENT_ID, authority=authority or Config.AUTHORITY, client_credential=Config.CLIENT_SECRET, token_cache=cache)
def get(self, tenant="common"): args = request.args try: self.__validate_request_args(args) except ValueError as e: return str(e) aad_instance = "https://login.windows.net" if ('aad_instance' in args): aad_instance = args['aad_instance'] client_id = args['client_id'] resource = args['resource'] client_credential = None if ('secret' in args): client_credential = args['secret'] else: client_credential = { "private_key": args['key'], "public_certificate": args['cert'] } claims = {"iss": client_id} path = urlparse(resource).path if (path.strip() in ['/', ""]): resource = urljoin(resource, '.default') app = msal.ConfidentialClientApplication( client_id=client_id, client_credential=client_credential, authority=urljoin(aad_instance, tenant), client_claims=claims) res = app.acquire_token_for_client([resource]) return res
def get_lab_app( env_client_id="LAB_APP_CLIENT_ID", env_client_secret="LAB_APP_CLIENT_SECRET", ): """Returns the lab app as an MSAL confidential client. Get it from environment variables if defined, otherwise fall back to use MSI. """ if os.getenv(env_client_id) and os.getenv(env_client_secret): # A shortcut mainly for running tests on developer's local development machine # or it could be setup on Travis CI # https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-settings # Data came from here # https://microsoft.sharepoint-df.com/teams/MSIDLABSExtended/SitePages/Rese.aspx#programmatic-access-info-for-lab-request-api logger.info("Using lab app defined by ENV variables %s and %s", env_client_id, env_client_secret) client_id = os.getenv(env_client_id) client_secret = os.getenv(env_client_secret) else: logger.info( "ENV variables %s and/or %s are not defined. Fall back to MSI.", env_client_id, env_client_secret) # See also https://microsoft.sharepoint-df.com/teams/MSIDLABSExtended/SitePages/Programmatically-accessing-LAB-API's.aspx raise unittest.SkipTest( "MSI-based mechanism has not been implemented yet") return msal.ConfidentialClientApplication( client_id, client_secret, authority="https://login.microsoftonline.com/" "72f988bf-86f1-41af-91ab-2d7cd011db47", # Microsoft tenant ID )
def get_auth_token(paramFile): result = None auth = paramFile["authority_type"] if auth == "msi": result = json.loads( requests.get(paramFile["authority"] + "&resource=" + paramFile["resource"] + "&client_id=" + paramFile["client_id"], headers={ "Metadata": "true" }).text) elif auth == "spn-cert" or auth == "spn-key": app = msal.ConfidentialClientApplication( paramFile["client_id"], authority=paramFile["authority"], client_credential={ "thumbprint": paramFile["thumbprint"], "private_key": open(paramFile['private_key_file']).read() } if auth == "spn-cert" else paramFile["client_secret"]) result = app.acquire_token_for_client( scopes=[paramFile["resource"] + "/.default"]) elif auth == "pat": result = {'access_token': paramFile["pat_token"]} else: # TODO: Raise exception result = "" return result
def _build_msal_app(cache=None, authority=None): # Return a ConfidentialClientApplication return msal.ConfidentialClientApplication( app.config['CLIENT_ID'], authority=authority or app.config['AUTHORITY'], client_credential=app.config['CLIENT_SECRET'], token_cache=cache)
def _build_msal_app(cache=None, authority=None): # TODO: Return a ConfidentialClientApplication conf_client = msal.ConfidentialClientApplication( \ Config.CLIENT_ID, authority=authority or Config.AUTHORITY, client_credential=Config.CLIENT_SECRET, token_cache=cache) #app.logger.info('INFO: CONF_CLIENT: {}'.format(conf_client)) return conf_client
def _build_msal_app(self, cache=None): return msal.ConfidentialClientApplication( self._client_id, authority="https://login.microsoftonline.com/" + self._tenant_id, client_credential=self._client_secret, token_cache=cache, )
def issue_token_api(student_id): msalCca = msal.ConfidentialClientApplication( "4b99bffa-0a45-4f7e-bcd6-d3712ec471fb", authority="https://login.microsoftonline.com/" + "1c5ffd4f-6cec-4ad2-954f-5e7eedb10095", client_credential="wuD7Q~O7X-S2M7TJQHdKfrcUGjQV84_OWveC0", ) accessToken = "" result = msalCca.acquire_token_for_client( scopes="bbb94529-53a3-4be5-a069-7eaf2712b826/.default") if "access_token" in result: accessToken = result['access_token'] request_file = open( "/Users/sachinvm/Desktop/CS Study/MsftHack/wasabi/qna-app/services/issuance_request_config.json" ) issuance_request = json.load(request_file) issuance_request["issuance"]["claims"]["studentId"] = student_id post_headers = { "content-type": "application/json", "Authorization": "Bearer " + accessToken } client_api_request_endpoint = "https://beta.did.msidentity.com/v1.0/" + "1c5ffd4f-6cec-4ad2-954f-5e7eedb10095" + "/verifiablecredentials/request" response = requests.post(client_api_request_endpoint, headers=post_headers, data=json.dumps(issuance_request)) return response.json()
def get_accesstoken(): '''Returns AAD token using MSAL''' response = None try: if config['AUTHENTICATION_MODE'].lower() == 'masteruser': # Create a public client to authorize the app with the AAD app clientapp = msal.PublicClientApplication(config['CLIENT_ID'], authority=config['AUTHORITY']) accounts = clientapp.get_accounts(username=config['POWER_BI_USER']) if accounts: # Retrieve Access token from cache if available response = clientapp.acquire_token_silent(config['SCOPE'], account=accounts[0]) if not response: # Make a client call if Access token is not available in cache response = clientapp.acquire_token_by_username_password(config['POWER_BI_USER'], config['POWER_BI_PASS'], scopes=config['SCOPE']) elif config['AUTHENTICATION_MODE'].lower() == 'serviceprincipal': authority = config['AUTHORITY'].replace('organizations', config['TENANT_ID']) clientapp = msal.ConfidentialClientApplication(config['CLIENT_ID'], client_credential=config['CLIENT_SECRET'], authority=authority) # Retrieve Access token from cache if available response = clientapp.acquire_token_silent(scopes=config['SCOPE'], account=None) if not response: # Make a client call if Access token is not available in cache response = clientapp.acquire_token_for_client(scopes=config['SCOPE']) try: return response['access_token'] except KeyError: raise Exception(response['error_description']) except Exception as ex: raise Exception('Error retrieving access token\n' + str(ex))
def get_auth_token(self): self.authority = self.connection_parameters.auth_host self.client_id = self.connection_parameters.auth_client_id self.client_credential = { "thumbprint": self.connection_parameters.auth_client_pem_thumprint, "private_key": self.connection_parameters.auth_client_pem_key } app = msal.ConfidentialClientApplication( self.client_id, authority=self.authority, client_credential=self.client_credential) # The pattern to acquire a token looks like this. result = None # Firstly, looks up a token from cache # Since we are looking for token for the current app, NOT for an end user, # notice we give account parameter as None. result = app.acquire_token_silent([self.client_id + "/.default"], account=None) if not result: logging.info( "No suitable token exists in cache. Let's get a new one from AAD." ) result = app.acquire_token_for_client( scopes=[self.client_id + "/.default"]) if not ("access_token" in result): logging.error("Could not find access token") sys.exit(1) else: return result["access_token"]
def test_subject_name_issuer_authentication(self): self.skipUnlessWithConfig(["client_id", "client_certificate"]) client_cert = self.config["client_certificate"] assert "private_key_path" in client_cert and "thumbprint" in client_cert if not "public_certificate" in client_cert: self.skipTest( "Skipping SNI test due to lack of public_certificate") with open(os.path.join(THIS_FOLDER, client_cert['private_key_path'])) as f: private_key = f.read() # Should be in PEM format with open(os.path.join(THIS_FOLDER, client_cert['public_certificate'])) as f: public_certificate = f.read() self.app = msal.ConfidentialClientApplication( self.config['client_id'], authority=self.config["authority"], client_credential={ "private_key": private_key, "thumbprint": self.config["thumbprint"], "public_certificate": public_certificate, }) scope = self.config.get("scope", []) result = self.app.acquire_token_for_client(scope) self.assertIn('access_token', result) self.assertCacheWorksForApp(result, scope)
def _build_context(self): """Build context when users make the first call. Also need to ensure client Id, tenant and secret are not null.""" if self._auth_context is None: self._auth_context = msal.ConfidentialClientApplication( self.client_id, authority='https://login.microsoftonline.com/' + self.tenant, client_credential=self.secret)
def __init__(self, client_id: str, client_secret: str, redirect_uri: str, scope: List[str], account_type: str = 'consumers', office365: bool = False, credentials: str = None): """Initializes the Graph Client. ### Parameters ---- client_id : str The application Client ID assigned when creating a new Microsoft App. client_secret : str The application Client Secret assigned when creating a new Microsoft App. redirect_uri : str The application Redirect URI assigned when creating a new Microsoft App. scope : List[str] The list of scopes you want the application to have access to. account_type : str, optional [description], by default 'common' office365 : bool, optional [description], by default False """ # printing lowercase letters = string.ascii_lowercase self.credentials = credentials self.token_dict = None self.client_id = client_id self.client_secret = client_secret self.api_version = 'v1.0' self.account_type = account_type self.redirect_uri = redirect_uri self.scope = scope self.state = ''.join(random.choice(letters) for i in range(10)) self.access_token = None self.refresh_token = None self.graph_session = None self.id_token = None self.base_url = self.RESOURCE + self.api_version + '/' self.office_url = self.OFFICE365_AUTHORITY_URL + self.OFFICE365_AUTH_ENDPOINT self.graph_url = self.AUTHORITY_URL + self.account_type + self.AUTH_ENDPOINT self.office365 = office365 # Initialize the Credential App. self.client_app = msal.ConfidentialClientApplication( client_id=self.client_id, authority=self.AUTHORITY_URL + self.account_type, client_credential=self.client_secret)
def _build_msal_app(cache=None, authority=None): settings = Settings() return msal.ConfidentialClientApplication( settings.get('ms-client_id'), authority=authority or settings.get('ms-authority'), client_credential=settings.get('ms-client_secret'), token_cache=cache, validate_authority=False)
def test_acquire_token_silent_with_an_empty_cache_should_return_none(self): config = self.get_lab_user( usertype="cloud", azureenvironment=self.environment, publicClient="no") app = msal.ConfidentialClientApplication( config['client_id'], authority=config['authority'], http_client=MinimalHttpClient()) result = app.acquire_token_silent(scopes=config['scope'], account=None) self.assertEqual(result, None)
def __init__(self): self.app = msal.ConfidentialClientApplication( client_id=self.client_id, client_credential=self.client_credential, authority=self.authority) # get new token self._access_token = self.app.acquire_token_for_client( scopes=self.scope)
def _build_msal_app(cache=None, authority=None): """Create a ConfidentialClientApplication""" return msal.ConfidentialClientApplication( client_id=Config.CLIENT_ID, client_credential=Config.CLIENT_SECRET, token_cache=cache, authority=authority or Config.AUTHORITY, )
def _build_msal_app(cache=None, authority=None): # TODO: Return a ConfidentialClientApplication app = msal.ConfidentialClientApplication( Config.CLIENT_ID, authority=Config.AUTHORITY, client_credential=Config.CLIENT_SECRET, token_cache=cache) return app
def __init__(self, tenant_id, client_id, client_secret, user_access_token): # type: (str, str, str, str) -> None self._confidential_client = msal.ConfidentialClientApplication( client_id=client_id, client_credential=client_secret, authority="https://{}/{}".format( AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, tenant_id)) self._user_token = user_access_token
def _build_msal_app(cache=None, authority=None): # TODO: Return a ConfidentialClientApplication app.logger.info('_build_msal_app: Login process using msal authN / authZ.') return msal.ConfidentialClientApplication( Config.CLIENT_ID, authority=authority or Config.AUTHORITY, client_credential=Config.CLIENT_SECRET, token_cache=cache)
def get_msal_app(cache=None): # Initialize the MSAL confidential client auth_app = msal.ConfidentialClientApplication( settings['app_id'], authority=settings['authority'], client_credential=settings['app_secret'], token_cache=cache) return auth_app
def _build_msal_app(cache=None, authority=None): client_id = app.config.get('CLIENT_ID') config_authority = app.config.get('AUTHORITY') return msal.ConfidentialClientApplication( client_id, authority=authority or config_authority, client_credential=app.config.get('CLIENT_SECRET'), token_cache=cache)
def get_confidential_client(): if AuthenticationHelper._confidential_client is None: print('Creating new confidential client') #This example only uses the default memory token cache and should not be used for production AuthenticationHelper._confidential_client = msal.ConfidentialClientApplication( os.environ.get("CLIENT_ID"), authority=os.environ.get("AUTHORITY"), client_credential=os.environ.get("CLIENT_SECRET")) return AuthenticationHelper._confidential_client
def _build_msal_app(cache=None, authority=Config.AUTHORITY): # TODO: Create and return a Confidential Client Application from msal cleint = msal.ConfidentialClientApplication( client_id=Config.CLIENT_ID, client_credential=Config.CLIENT_SECRET, authority=Config.AUTHORITY or authority, token_cache=cache) return cleint
def authenticate_for_app(self): authority = self.AUTHORITY_URL + self.account_type + self.TOKEN_ENDPOINT token = msal.ConfidentialClientApplication( self.client_id, authority=authority, client_credential=self.client_secret).acquire_token_for_client( scopes=self.SCOPE) self.set_token(token)