How to use the msrest.authentication.BasicTokenAuthentication function in msrest

To help you get started, we’ve selected a few msrest examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure / azure-sdk-for-java / AutoRest / Generators / Python / Azure.Python.Tests / AcceptanceTests / xms_request_clientid_tests.py View on Github external
def test_custom_named_request_id_param_grouping(self):

        validSubscription = '1234-5678-9012-3456'
        expectedRequestId = '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'

        cred = BasicTokenAuthentication({"access_token":123})
        client = AutoRestAzureSpecialParametersTestClient(cred, validSubscription, base_url="http://localhost:3000")
        
        group = models.HeaderCustomNamedRequestIdParamGroupingParameters(foo_client_request_id=expectedRequestId)
        response = client.header.custom_named_request_id_param_grouping(group, raw=True)
        self.assertEqual("123", response.response.headers.get("foo-request-id"))
github Azure / autorest / src / generator / AutoRest.Python.Azure.Tests / AcceptanceTests / xms_request_clientid_tests.py View on Github external
def test_xms_request_client_id_in_client(self):
        validSubscription = '1234-5678-9012-3456'
        expectedRequestId = '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'

        cred = BasicTokenAuthentication({"access_token":123})
        client = AutoRestAzureSpecialParametersTestClient(cred, validSubscription, base_url="http://localhost:3000")
        client.config.generate_client_request_id = False
        client.xms_client_request_id.get()
github Azure / azure-sdk-for-java / AutoRest / Generators / Python / Azure.Python.Tests / AcceptanceTests / xms_request_clientid_tests.py View on Github external
def test_xms_request_client_id(self):

        validSubscription = '1234-5678-9012-3456'
        validClientId = '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'

        cred = BasicTokenAuthentication({"access_token":123})
        client = AutoRestAzureSpecialParametersTestClient(cred, validSubscription, base_url="http://localhost:3000")

        custom_headers = {"x-ms-client-request-id": validClientId }

        result1 = client.xms_client_request_id.get(custom_headers = custom_headers, raw=True)
        #TODO: should we put the x-ms-request-id into response header of swagger spec?
        self.assertEqual("123", result1.response.headers.get("x-ms-request-id"))

        result2 = client.xms_client_request_id.param_get(validClientId, raw=True)
        self.assertEqual("123", result2.response.headers.get("x-ms-request-id"))
github Azure / autorest / src / generator / AutoRest.Python.Azure.Tests / AcceptanceTests / xms_request_clientid_tests.py View on Github external
def test_xms_request_client_id(self):

        validSubscription = '1234-5678-9012-3456'
        validClientId = '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'

        cred = BasicTokenAuthentication({"access_token":123})
        client = AutoRestAzureSpecialParametersTestClient(cred, validSubscription, base_url="http://localhost:3000")

        custom_headers = {"x-ms-client-request-id": validClientId }

        result1 = client.xms_client_request_id.get(custom_headers = custom_headers, raw=True)
        #TODO: should we put the x-ms-request-id into response header of swagger spec?
        self.assertEqual("123", result1.response.headers.get("x-ms-request-id"))

        result2 = client.xms_client_request_id.param_get(validClientId, raw=True)
        self.assertEqual("123", result2.response.headers.get("x-ms-request-id"))
github Azure / azure-sdk-for-python / sdk / core / azure-mgmt-core / azure / mgmt / core / azure_active_directory.py View on Github external
err_msg = "MSI: Failed to retrieve a token from '{}' with an error of '{}'.".format(
            request_uri, err
        )
        _LOGGER.critical(err_msg)
        raise RuntimeError(err_msg)
    _LOGGER.debug('MSI: token retrieved')
    token_entry = result.json()
    return token_entry['token_type'], token_entry['access_token'], token_entry


def _is_app_service():
    # Might be discussed if we think it's not robust enough
    return 'APPSETTING_WEBSITE_SITE_NAME' in os.environ


class MSIAuthentication(BasicTokenAuthentication):
    """Credentials object for MSI authentication,.

    Optional kwargs may include:

    - client_id: Identifies, by Azure AD client id, a specific explicit identity to use when authenticating to Azure AD. Mutually exclusive with object_id and msi_res_id.
    - object_id: Identifies, by Azure AD object id, a specific explicit identity to use when authenticating to Azure AD. Mutually exclusive with client_id and msi_res_id.
    - msi_res_id: Identifies, by ARM resource id, a specific explicit identity to use when authenticating to Azure AD. Mutually exclusive with client_id and object_id.
    - cloud_environment (azure.mgmt.core.azure_cloud.Cloud): A targeted cloud environment
    - resource (str): Alternative authentication resource, default
      is 'https://management.core.windows.net/'.

    .. versionadded:: 0.4.14
    """

    def __init__(self, port=50342, **kwargs):
        super(MSIAuthentication, self).__init__(None)
github Azure / azure-cli / src / azure-cli-core / azure / cli / core / _profile.py View on Github external
def _find_using_common_tenant(self, access_token, resource):
        import adal
        from msrest.authentication import BasicTokenAuthentication

        all_subscriptions = []
        token_credential = BasicTokenAuthentication({'access_token': access_token})
        client = self._arm_client_factory(token_credential)
        tenants = client.tenants.list()
        for t in tenants:
            tenant_id = t.tenant_id
            temp_context = self._create_auth_context(tenant_id)
            try:
                temp_credentials = temp_context.acquire_token(resource, self.user_id, _CLIENT_ID)
            except adal.AdalError as ex:
                # because user creds went through the 'common' tenant, the error here must be
                # tenant specific, like the account was disabled. For such errors, we will continue
                # with other tenants.
                logger.warning("Failed to authenticate '%s' due to error '%s'", t, ex)
                continue
            subscriptions = self._find_using_specific_tenant(
                tenant_id,
                temp_credentials[_ACCESS_TOKEN])
github dotnet / arcade / src / Microsoft.DotNet.Helix / Sdk / tools / azure-pipelines / reporter / azure_devops_result_publisher.py View on Github external
def get_credentials(self) -> BasicTokenAuthentication:
        if self.access_token:
            return BasicTokenAuthentication({'access_token': self.access_token})

        token = get_env("VSTS_PAT")
        return BasicAuthentication("ignored", token)
github Azure / msrest-for-python / msrest / authentication.py View on Github external
def signed_session(self, session=None):
        # type: (Optional[requests.Session]) -> requests.Session
        """Create requests session with any required auth headers
        applied.

        If a session object is provided, configure it directly. Otherwise,
        create a new session and return it.

        :param session: The session to configure for authentication
        :type session: requests.Session
        :rtype: requests.Session
        """
        session = super(BasicTokenAuthentication, self).signed_session(session)
        header = "{} {}".format(self.scheme, self.token['access_token'])
        session.headers['Authorization'] = header
        return session
github Azure / azure-sdk-for-python / azure-keyvault / azure / keyvault / custom / key_vault_client.py View on Github external
def __init__(self, credentials):
        """The key vault client performs cryptographic key operations and vault operations against the Key Vault service.

        :ivar config: Configuration for client.
        :vartype config: KeyVaultClientConfiguration

        :param credentials: Credentials needed for the client to connect to Azure.
        :type credentials: :mod:`A msrestazure Credentials
         object` or :mod:`A KeyVaultAuthentication
         object`
        """

        # if the supplied credentials instance is not derived from KeyVaultAuthBase but is an AAD credential type
        if not isinstance(credentials, KeyVaultAuthentication) and isinstance(credentials, BasicTokenAuthentication):

            # wrap the supplied credentials with a KeyVaultAuthentication instance. Use that for the credentials supplied to the base client
            credentials = KeyVaultAuthentication(credentials=credentials)

        super(CustomKeyVaultClient, self).__init__(credentials)
github microsoft / msticpy / msticpy / common / keyvault_client.py View on Github external
def get_vault_uri(self, vault_name: str) -> str:
        """
        Return the URI for a vault name.

        Parameters
        ----------
        vault_name : str
            The Vault name.

        Returns
        -------
        str
            Vault URI.

        """
        cred = BasicTokenAuthentication({"access_token": self.auth_client.token})
        mgmt = KeyVaultManagementClient(cred, self.subscription_id)
        try:
            vault = mgmt.vaults.get(self.resource_group, vault_name)
        except (CloudError, ResourceNotFoundError) as cloud_err:
            raise MPKeyVaultMissingVaultException(
                f"Vault {vault_name} not found.", cloud_err
            )
        return vault.properties.vault_uri