def create_authentication(client):
    # pylint: disable=protected-access
    try:
        # ignore mypy's warning because token_type is Optional
        token_type = client._credential.token_type  # type: ignore
    except AttributeError:
        token_type = TOKEN_TYPE_JWT
    if token_type == TOKEN_TYPE_SASTOKEN:
        auth = authentication.JWTTokenAuth(
            client._auth_uri,
            client._auth_uri,
            functools.partial(client._credential.get_token, client._auth_uri),
            token_type=token_type,
            timeout=client._config.auth_timeout,
            http_proxy=client._config.http_proxy,
            transport_type=client._config.transport_type,
        )
        auth.update_token()
        return auth
    return authentication.JWTTokenAuth(
        client._auth_uri,
        client._auth_uri,
        functools.partial(client._credential.get_token, JWT_TOKEN_SCOPE),
        token_type=token_type,
        timeout=client._config.auth_timeout,
        http_proxy=client._config.http_proxy,
        transport_type=client._config.transport_type,
    )
Esempio n. 2
0
 def _create_auth(self):
     # type: () -> authentication.JWTTokenAuth
     """
     Create an ~uamqp.authentication.SASTokenAuth instance to authenticate
     the session.
     """
     try:
         token_type = self._credential.token_type
     except AttributeError:
         token_type = b'jwt'
     if token_type == b"servicebus.windows.net:sastoken":
         auth = authentication.JWTTokenAuth(
             self._auth_uri,
             self._auth_uri,
             functools.partial(self._credential.get_token, self._auth_uri),
             token_type=token_type,
             timeout=self._config.auth_timeout,
             http_proxy=self._config.http_proxy,
             transport_type=self._config.transport_type)
         auth.update_token()
         return auth
     return authentication.JWTTokenAuth(
         self._auth_uri,
         self._auth_uri,
         functools.partial(self._credential.get_token, JWT_TOKEN_SCOPE),
         token_type=token_type,
         timeout=self._config.auth_timeout,
         http_proxy=self._config.http_proxy,
         transport_type=self._config.transport_type)
Esempio n. 3
0
def test_event_hubs_custom_end_point():
    sas_token = authentication.SASTokenAuth(
        "fake_audience",
        "fake_uri",
        "fake_token",
        expires_in=timedelta(10),
        custom_endpoint_hostname="123.45.67.89")
    assert sas_token.hostname == b"123.45.67.89"

    sas_token = authentication.SASTokenAuth.from_shared_access_key(
        "fake_uri",
        "fake_key_name",
        "fake_key",
        custom_endpoint_hostname="123.45.67.89")
    assert sas_token.hostname == b"123.45.67.89"

    def fake_get_token():
        return "fake get token"

    jwt_token = authentication.JWTTokenAuth(
        "fake_audience",
        "fake_uri",
        fake_get_token,
        custom_endpoint_hostname="123.45.67.89")
    assert jwt_token.hostname == b"123.45.67.89"
Esempio n. 4
0
    def _create_auth(self, username=None, password=None):
        """
        Create an ~uamqp.authentication.SASTokenAuth instance to authenticate
        the session.

        :param username: The name of the shared access policy.
        :type username: str
        :param password: The shared access key.
        :type password: str
        """
        http_proxy = self._config.http_proxy
        transport_type = self._config.transport_type
        auth_timeout = self._config.auth_timeout

        # TODO: the following code can be refactored to create auth from classes directly instead of using if-else
        if isinstance(self._credential, EventHubSharedKeyCredential):  # pylint:disable=no-else-return
            username = username or self._auth_config['username']
            password = password or self._auth_config['password']
            if "@sas.root" in username:
                return authentication.SASLPlain(self._host,
                                                username,
                                                password,
                                                http_proxy=http_proxy,
                                                transport_type=transport_type)
            return authentication.SASTokenAuth.from_shared_access_key(
                self._auth_uri,
                username,
                password,
                timeout=auth_timeout,
                http_proxy=http_proxy,
                transport_type=transport_type)

        elif isinstance(self._credential, EventHubSASTokenCredential):
            token = self._credential.get_sas_token()
            try:
                expiry = int(parse_sas_token(token)['se'])
            except (KeyError, TypeError, IndexError):
                raise ValueError(
                    "Supplied SAS token has no valid expiry value.")
            return authentication.SASTokenAuth(self._auth_uri,
                                               self._auth_uri,
                                               token,
                                               expires_at=expiry,
                                               timeout=auth_timeout,
                                               http_proxy=http_proxy,
                                               transport_type=transport_type)

        else:  # Azure credential
            get_jwt_token = functools.partial(
                self._credential.get_token,
                'https://eventhubs.azure.net//.default')
            return authentication.JWTTokenAuth(self._auth_uri,
                                               self._auth_uri,
                                               get_jwt_token,
                                               http_proxy=http_proxy,
                                               transport_type=transport_type)
 def _create_auth(self):
     # type: () -> authentication.JWTTokenAuth
     """
     Create an ~uamqp.authentication.SASTokenAuth instance to authenticate
     the session.
     """
     try:
         # ignore mypy's warning because token_type is Optional
         token_type = self._credential.token_type  # type: ignore
     except AttributeError:
         token_type = b"jwt"
     if token_type == b"servicebus.windows.net:sastoken":
         auth = authentication.JWTTokenAuth(
             self._auth_uri,
             self._auth_uri,
             functools.partial(self._credential.get_token, self._auth_uri),
             token_type=token_type,
             timeout=self._config.auth_timeout,
             http_proxy=self._config.http_proxy,
             transport_type=self._config.transport_type,
             custom_endpoint_hostname=self._config.custom_endpoint_hostname,
             port=self._config.connection_port,
             verify=self._config.connection_verify,
         )
         auth.update_token()
         return auth
     return authentication.JWTTokenAuth(
         self._auth_uri,
         self._auth_uri,
         functools.partial(self._credential.get_token, JWT_TOKEN_SCOPE),
         token_type=token_type,
         timeout=self._config.auth_timeout,
         http_proxy=self._config.http_proxy,
         transport_type=self._config.transport_type,
         custom_endpoint_hostname=self._config.custom_endpoint_hostname,
         port=self._config.connection_port,
         verify=self._config.connection_verify,
         refresh_window=300,
     )
    def _create_auth(self):
        """
        Create an ~uamqp.authentication.SASTokenAuth instance to authenticate
        the session.
        """
        http_proxy = self._config.http_proxy
        transport_type = self._config.transport_type
        auth_timeout = self._config.auth_timeout

        # TODO: the following code can be refactored to create auth from classes directly instead of using if-else
        if isinstance(self._credential, EventHubSharedKeyCredential):  # pylint:disable=no-else-return
            username = self._credential.policy
            password = self._credential.key
            if "@sas.root" in username:
                return authentication.SASLPlain(self._address.hostname,
                                                username,
                                                password,
                                                http_proxy=http_proxy,
                                                transport_type=transport_type)
            return authentication.SASTokenAuth.from_shared_access_key(
                self._auth_uri,
                username,
                password,
                timeout=auth_timeout,
                http_proxy=http_proxy,
                transport_type=transport_type)

        elif isinstance(self._credential, EventHubSASTokenCredential):
            token = self._credential.get_sas_token()
            try:
                expiry = int(parse_sas_token(token)['se'])
            except (KeyError, TypeError, IndexError):
                raise ValueError(
                    "Supplied SAS token has no valid expiry value.")
            return authentication.SASTokenAuth(self._auth_uri,
                                               self._auth_uri,
                                               token,
                                               expires_at=expiry,
                                               timeout=auth_timeout,
                                               http_proxy=http_proxy,
                                               transport_type=transport_type)

        else:  # Azure credential
            get_jwt_token = functools.partial(self._credential.get_token,
                                              JWT_TOKEN_SCOPE)
            return authentication.JWTTokenAuth(self._auth_uri,
                                               self._auth_uri,
                                               get_jwt_token,
                                               http_proxy=http_proxy,
                                               transport_type=transport_type)
def test_event_hubs_send_override_token_refresh_window(live_eventhub_config):
    uri = "sb://{}/{}".format(live_eventhub_config['hostname'],
                              live_eventhub_config['event_hub'])
    target = "amqps://{}/{}/Partitions/0".format(
        live_eventhub_config['hostname'], live_eventhub_config['event_hub'])
    token = [None]

    def get_token():
        return _AccessToken(token[0], expiry)

    jwt_auth = authentication.JWTTokenAuth(
        uri,
        uri,
        get_token,
        refresh_window=300  # set refresh window to be 5 mins
    )

    send_client = uamqp.SendClient(target, auth=jwt_auth, debug=False)

    # use token of which the valid remaining time < refresh window
    expiry = int(time.time()) + (60 * 4 + 30)  # 4.5 minutes
    token[0] = utils.create_sas_token(
        live_eventhub_config['key_name'].encode(),
        live_eventhub_config['access_key'].encode(),
        uri.encode(),
        expiry=timedelta(minutes=4, seconds=30))

    for _ in range(3):
        message = uamqp.message.Message(body='Hello World')
        send_client.send_message(message)

    auth_status = constants.CBSAuthStatus(jwt_auth._cbs_auth.get_status())
    assert auth_status == constants.CBSAuthStatus.RefreshRequired

    # update token, the valid remaining time > refresh window
    expiry = int(time.time()) + (60 * 5 + 30)  # 5.5 minutes
    token[0] = utils.create_sas_token(
        live_eventhub_config['key_name'].encode(),
        live_eventhub_config['access_key'].encode(),
        uri.encode(),
        expiry=timedelta(minutes=5, seconds=30))

    for _ in range(3):
        message = uamqp.message.Message(body='Hello World')
        send_client.send_message(message)

    auth_status = constants.CBSAuthStatus(jwt_auth._cbs_auth.get_status())
    assert auth_status == constants.CBSAuthStatus.Ok
    send_client.close()
def authenticate_client_by_jwt():
    # Create the JWTTokenAuth object
    auth_uri = "<amqp endpoint uri for authentication>"  # The AMQP endpoint URI for authentication.
    token_audience = "<token audience>"  # The token audience field.
    auth = authentication.JWTTokenAuth(audience=token_audience,
                                       uri=auth_uri,
                                       get_token=get_token)

    # Instantiate the SendClient with the JWTTokenAuth object
    target = "<target amqp service endpoint>"  # The target AMQP service endpoint.
    send_client = SendClient(target=target, auth=auth)

    # Send a message
    message = Message(b'data')
    send_client.send_message(message)
    send_client.close()