def create_from_sastoken(cls, sastoken, **kwargs): """Instantiate the client from a pre-created SAS Token string :param str sastoken: The SAS Token string :param str server_verification_cert: Configuration Option. The trusted certificate chain. Necessary when using connecting to an endpoint which has a non-standard root of trust, such as a protocol gateway. :param bool websockets: Configuration Option. Default is False. Set to true if using MQTT over websockets. :param cipher: Configuration Option. Cipher suite(s) for TLS/SSL, as a string in "OpenSSL cipher list format" or as a list of cipher suite strings. :type cipher: str or list(str) :param str product_info: Configuration Option. Default is empty string. The string contains arbitrary product info which is appended to the user agent string. :param proxy_options: Options for sending traffic through proxy servers. :type proxy_options: :class:`azure.iot.device.ProxyOptions` :param int keep_alive: Maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker. If not provided default value of 60 secs will be used. :raises: TypeError if given an unsupported parameter. :raises: ValueError if the sastoken parameter is invalid. """ # Ensure no invalid kwargs were passed by the user excluded_kwargs = ["sastoken_ttl"] _validate_kwargs(exclude=excluded_kwargs, **kwargs) # Create SasToken object from string try: sastoken_o = st.NonRenewableSasToken(sastoken) except st.SasTokenError as e: new_err = ValueError("Invalid SasToken provided") new_err.__cause__ = e raise new_err # Extract values from SasToken vals = _extract_sas_uri_values(sastoken_o.resource_uri) if cls.__name__ == "IoTHubDeviceClient" and vals["module_id"]: raise ValueError("Provided SasToken is for a module") if cls.__name__ == "IoTHubModuleClient" and not vals["module_id"]: raise ValueError("Provided SasToken is for a device") if sastoken_o.expiry_time < int(time.time()): raise ValueError("Provided SasToken has already expired") # Pipeline Config setup config_kwargs = _get_config_kwargs(**kwargs) pipeline_configuration = pipeline.IoTHubPipelineConfig( device_id=vals["device_id"], module_id=vals["module_id"], hostname=vals["hostname"], sastoken=sastoken_o, **config_kwargs) if cls.__name__ == "IoTHubDeviceClient": pipeline_configuration.blob_upload = True # Blob Upload is a feature on Device Clients # Pipeline setup http_pipeline = pipeline.HTTPPipeline(pipeline_configuration) mqtt_pipeline = pipeline.MQTTPipeline(pipeline_configuration) return cls(mqtt_pipeline, http_pipeline)
def _replace_user_supplied_sastoken(self, sastoken_str): """ Replaces the pipeline's NonRenewableSasToken with a new one based on a provided sastoken string. Also does validation. This helper only updates the PipelineConfig - it does not reauthorize the connection. """ if not isinstance(self._mqtt_pipeline.pipeline_configuration.sastoken, st.NonRenewableSasToken): raise exceptions.ClientError( "Cannot update sastoken when client was not created with one") # Create new SasToken try: new_token_o = st.NonRenewableSasToken(sastoken_str) except st.SasTokenError as e: new_err = ValueError("Invalid SasToken provided") new_err.__cause__ = e raise new_err # Extract values from SasToken vals = _extract_sas_uri_values(new_token_o.resource_uri) # Validate new token if type(self).__name__ == "IoTHubDeviceClient" and vals["module_id"]: raise ValueError("Provided SasToken is for a module") if type(self ).__name__ == "IoTHubModuleClient" and not vals["module_id"]: raise ValueError("Provided SasToken is for a device") if self._mqtt_pipeline.pipeline_configuration.device_id != vals[ "device_id"]: raise ValueError( "Provided SasToken does not match existing device id") if self._mqtt_pipeline.pipeline_configuration.module_id != vals[ "module_id"]: raise ValueError( "Provided SasToken does not match existing module id") if self._mqtt_pipeline.pipeline_configuration.hostname != vals[ "hostname"]: raise ValueError( "Provided SasToken does not match existing hostname") if new_token_o.expiry_time < int(time.time()): raise ValueError("Provided SasToken has already expired") # Set token # NOTE: We only need to set this on MQTT because this is a reference to the same object # that is stored in HTTP. The HTTP pipeline is updated implicitly. self._mqtt_pipeline.pipeline_configuration.sastoken = new_token_o