Search in sources :

Example 11 with IotHubSasToken

use of com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken in project azure-iot-sdk-java by Azure.

the class IotHubSasTokenTest method signatureSetCorrectly.

// Tests_SRS_IOTHUBSASTOKEN_11_005: [The signature shall be correctly computed and set.]
// Tests_SRS_IOTHUBSASTOKEN_11_006: [The function shall return the string representation of the SAS token.]
@Test
public void signatureSetCorrectly() throws URISyntaxException {
    final long expiryTime = 100;
    final String signature = "sample-sig";
    final IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, new Class[] { String.class, String.class, String.class, String.class }, "iothub.sample-iothub-hostname.net", "sample-device-ID", "sample-device-key", null);
    new NonStrictExpectations() {

        {
            mockSig.toString();
            result = signature;
        }
    };
    IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubConnectionString), expiryTime);
    String tokenStr = token.toString();
    // extract the value assigned to sig.
    int signatureKeyIdx = tokenStr.indexOf("sig=");
    int signatureStartIdx = signatureKeyIdx + 4;
    int signatureEndIdx = tokenStr.indexOf("&", signatureStartIdx);
    if (signatureEndIdx == -1) {
        signatureEndIdx = tokenStr.length();
    }
    String testSignature = tokenStr.substring(signatureStartIdx, signatureEndIdx);
    final String expectedSignature = signature;
    assertThat(testSignature, is(expectedSignature));
}
Also used : DeviceClientConfig(com.microsoft.azure.sdk.iot.device.DeviceClientConfig) IotHubConnectionString(com.microsoft.azure.sdk.iot.device.IotHubConnectionString) IotHubSasToken(com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken) IotHubConnectionString(com.microsoft.azure.sdk.iot.device.IotHubConnectionString) NonStrictExpectations(mockit.NonStrictExpectations) Test(org.junit.Test)

Example 12 with IotHubSasToken

use of com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken in project azure-iot-sdk-java by Azure.

the class IotHubSasTokenTest method sasTokenHasCorrectFormat.

// Tests_SRS_IOTHUBSASTOKEN_11_001: [The SAS token shall have the format "SharedAccessSignature sig=<signature>&se=<expiryTime>&sr=<resourceURI>". The params can be in any order.]
@Test
public void sasTokenHasCorrectFormat() throws URISyntaxException {
    final long expiryTime = 100;
    final String signature = "sample-sig";
    final IotHubConnectionString iotHubConnectionString = Deencapsulation.newInstance(IotHubConnectionString.class, new Class[] { String.class, String.class, String.class, String.class }, "iothub.sample-iothub-hostname.net", "sample-device-ID", "sample-device-key", null);
    new NonStrictExpectations() {

        {
            mockSig.toString();
            result = signature;
        }
    };
    IotHubSasToken token = new IotHubSasToken(new DeviceClientConfig(iotHubConnectionString), expiryTime);
    String tokenStr = token.toString();
    // assert that sig, se and sr exist in the token in any order.
    assertThat(tokenStr.indexOf("SharedAccessSignature "), is(not(-1)));
    assertThat(tokenStr.indexOf("sig="), is(not(-1)));
    assertThat(tokenStr.indexOf("se="), is(not(-1)));
    assertThat(tokenStr.indexOf("sr="), is(not(-1)));
}
Also used : DeviceClientConfig(com.microsoft.azure.sdk.iot.device.DeviceClientConfig) IotHubConnectionString(com.microsoft.azure.sdk.iot.device.IotHubConnectionString) IotHubSasToken(com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken) IotHubConnectionString(com.microsoft.azure.sdk.iot.device.IotHubConnectionString) NonStrictExpectations(mockit.NonStrictExpectations) Test(org.junit.Test)

Example 13 with IotHubSasToken

use of com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken in project azure-iot-sdk-java by Azure.

the class MqttIotHubConnection method open.

/**
     * Establishes a connection for the device and IoT Hub given in the client
     * configuration. If the connection is already open, the function shall do
     * nothing.
     *
     * @throws IOException if a connection could not to be established.
     */
public void open() throws IOException {
    synchronized (MQTT_CONNECTION_LOCK) {
        // the function shall do nothing.]
        if (this.state == State.OPEN) {
            return;
        }
        // with an IoT Hub using the provided host name, user name, device ID, and sas token.]
        try {
            IotHubSasToken sasToken = new IotHubSasToken(this.config, System.currentTimeMillis() / 1000L + this.config.getTokenValidSecs() + 1L);
            this.iotHubUserPassword = sasToken.toString();
            String clientIdentifier = "DeviceClientType=" + URLEncoder.encode(TransportUtils.JAVA_DEVICE_CLIENT_IDENTIFIER + TransportUtils.CLIENT_VERSION, "UTF-8");
            this.iotHubUserName = this.config.getIotHubHostname() + "/" + this.config.getDeviceId() + "/" + TWIN_API_VERSION + "/" + clientIdentifier;
            this.deviceMessaging = new MqttMessaging(SSL_PREFIX + this.config.getIotHubHostname() + SSL_PORT_SUFFIX, this.config.getDeviceId(), this.iotHubUserName, this.iotHubUserPassword, this.config.getIotHubSSLContext());
            this.deviceMethod = new MqttDeviceMethod();
            this.deviceTwin = new MqttDeviceTwin();
            this.deviceMessaging.start();
            this.state = State.OPEN;
        } catch (Exception e) {
            this.state = State.CLOSED;
            // for any reason, the function shall throw an IOException.]
            if (this.deviceMethod != null) {
                this.deviceMethod.stop();
            }
            if (this.deviceTwin != null) {
                this.deviceTwin.stop();
            }
            if (this.deviceMessaging != null) {
                this.deviceMessaging.stop();
            }
            throw new IOException(e.getMessage(), e.getCause());
        }
    }
}
Also used : IotHubSasToken(com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken) IOException(java.io.IOException) IOException(java.io.IOException)

Example 14 with IotHubSasToken

use of com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken in project azure-iot-sdk-java by Azure.

the class HttpsIotHubConnection method sendEvent.

/**
     * Sends an event message.
     *
     * @param msg the event message.
     *
     * @return the ResponseMessage including status code and payload from sending the event message.
     *
     * @throws IOException if the IoT Hub could not be reached.
     */
public ResponseMessage sendEvent(HttpsMessage msg) throws IOException {
    synchronized (HTTPS_CONNECTION_LOCK) {
        String iotHubHostname = this.config.getIotHubHostname();
        String deviceId = this.config.getDeviceId();
        int readTimeoutMillis = this.config.getReadTimeoutMillis();
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_002: [The function shall send a request to the URL 'https://[iotHubHostname]/devices/[deviceId]/messages/events?api-version=2016-02-03'.]
        IotHubEventUri eventUri = new IotHubEventUri(iotHubHostname, deviceId);
        URL eventUrl = new URL("https://" + eventUri.toString());
        IotHubSasToken sasToken = new IotHubSasToken(this.config, System.currentTimeMillis() / 1000L + this.config.getTokenValidSecs() + 1L);
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_003: [The function shall send a POST request.]
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_004: [The function shall set the request body to the message body.]
        HttpsRequest request = new HttpsRequest(eventUrl, HttpsMethod.POST, msg.getBody());
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_005: [The function shall write each message property as a request header.]
        for (MessageProperty property : msg.getProperties()) {
            request.setHeaderField(property.getName(), property.getValue());
        }
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_006: [The function shall set the request read timeout to be the configuration parameter readTimeoutMillis.]
        request.setReadTimeoutMillis(readTimeoutMillis).setHeaderField("authorization", sasToken.toString()).setHeaderField("iothub-to", eventUri.getPath()).setHeaderField("content-type", msg.getContentType());
        //Codes_SRS_HTTPSIOTHUBCONNECTION_25_040: [The function shall set the IotHub SSL context by calling setSSLContext on the request.]
        request.setSSLContext(this.config.getIotHubSSLContext());
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_012: [If the IoT Hub could not be reached, the function shall throw an IOException.]
        HttpsResponse response = request.send();
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_010: [The function shall return a ResponseMessage with the status and payload.]
        IotHubStatusCode status = IotHubStatusCode.getIotHubStatusCode(response.getStatus());
        byte[] body = response.getBody();
        return new ResponseMessage(body, status);
    }
}
Also used : IotHubSasToken(com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken) URL(java.net.URL)

Example 15 with IotHubSasToken

use of com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken in project azure-iot-sdk-java by Azure.

the class HttpsIotHubConnection method sendMessageResult.

/**
     * Sends the message result for the previously received
     * message.
     *
     * @param result the message result (one of {@link IotHubMessageResult#COMPLETE},
     *               {@link IotHubMessageResult#ABANDON}, or {@link IotHubMessageResult#REJECT}).
     *
     * @throws IllegalStateException if {@code sendMessageResult} is called before
     * {@link #receiveMessage()} is called.
     * @throws IOException if the IoT Hub could not be reached.
     */
public void sendMessageResult(IotHubMessageResult result) throws IOException {
    synchronized (HTTPS_CONNECTION_LOCK) {
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_039: [If the function is called before receiveMessage() returns a message, the function shall throw an IllegalStateException.]
        if (this.messageEtag == null) {
            throw new IllegalStateException("Cannot send a message " + "result before a message is received.");
        }
        String iotHubHostname = this.config.getIotHubHostname();
        String deviceId = this.config.getDeviceId();
        int readTimeoutMillis = this.config.getReadTimeoutMillis();
        String resultUri = "https://";
        String resultPath;
        URL resultUrl;
        HttpsRequest request;
        switch(result) {
            case COMPLETE:
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_024: [If the result is COMPLETE, the function shall send a request to the URL 'https://[iotHubHostname]/devices/[deviceId]/messages/devicebound/[eTag]?api-version=2016-02-03'.]
                IotHubCompleteUri completeUri = new IotHubCompleteUri(iotHubHostname, deviceId, this.messageEtag);
                resultUri += completeUri.toString();
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_026: [If the result is COMPLETE, the function shall set the header field 'iothub-to' to be '/devices/[deviceId]/messages/devicebound/[eTag]'.]
                resultPath = completeUri.getPath();
                resultUrl = new URL(resultUri);
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_025: [If the result is COMPLETE, the function shall send a DELETE request.]
                request = new HttpsRequest(resultUrl, HttpsMethod.DELETE, new byte[0]);
                break;
            case ABANDON:
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_027: [If the result is ABANDON, the function shall send a request to the URL 'https://[iotHubHostname]/devices/[deviceId]/messages/devicebound/[eTag]/abandon?api-version=2016-02-03'.]
                IotHubAbandonUri abandonUri = new IotHubAbandonUri(iotHubHostname, deviceId, this.messageEtag);
                resultUri += abandonUri.toString();
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_029: [If the result is ABANDON, the function shall set the header field 'iothub-to' to be '/devices/[deviceId]/messages/devicebound/[eTag]/abandon'.]
                resultPath = abandonUri.getPath();
                resultUrl = new URL(resultUri);
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_028: [If the result is ABANDON, the function shall send a POST request.]
                // The IoT Hub service requires the content-length header to be
                // set but the Java SE connection omits content-length
                // if content-length == 0. We include a placeholder body to
                // make the connection include a content-length.
                request = new HttpsRequest(resultUrl, HttpsMethod.POST, new byte[1]);
                break;
            case REJECT:
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_030: [If the result is REJECT, the function shall send a request to the URL 'https://[iotHubHostname]/devices/[deviceId]/messages/devicebound/[eTag]??reject=true&api-version=2016-02-03' (the query parameters can be in any order).]
                IotHubRejectUri rejectUri = new IotHubRejectUri(iotHubHostname, deviceId, this.messageEtag);
                resultUri += rejectUri.toString();
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_032: [If the result is REJECT, the function shall set the header field 'iothub-to' to be '/devices/[deviceId]/messages/devicebound/[eTag]'.]
                resultPath = rejectUri.getPath();
                resultUrl = new URL(resultUri);
                // Codes_SRS_HTTPSIOTHUBCONNECTION_11_031: [If the result is REJECT, the function shall send a DELETE request.]
                request = new HttpsRequest(resultUrl, HttpsMethod.DELETE, new byte[0]);
                break;
            default:
                // should never happen.
                throw new IllegalStateException("Invalid message result specified.");
        }
        IotHubSasToken sasToken = new IotHubSasToken(this.config, System.currentTimeMillis() / 1000L + this.config.getTokenValidSecs() + 1L);
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_033: [The function shall set the request read timeout to be the configuration parameter readTimeoutMillis.]
        request.setReadTimeoutMillis(readTimeoutMillis).setHeaderField("authorization", sasToken.toString()).setHeaderField("iothub-to", resultPath).setHeaderField("if-match", this.messageEtag);
        //Codes_SRS_HTTPSIOTHUBCONNECTION_25_042: [The function shall set the IotHub SSL context by calling setSSLContext on the request.]
        request.setSSLContext(this.config.getIotHubSSLContext());
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_037: [If the IoT Hub could not be reached, the function shall throw an IOException.]
        HttpsResponse response = request.send();
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_038: [If the IoT Hub status code in the response is not OK_EMPTY, the function shall throw an IOException.]
        IotHubStatusCode resultStatus = IotHubStatusCode.getIotHubStatusCode(response.getStatus());
        if (resultStatus != IotHubStatusCode.OK_EMPTY) {
            String errMsg = String.format("Sending message result failed with status %s.%n", resultStatus.name());
            throw new IOException(errMsg);
        }
    }
}
Also used : IotHubSasToken(com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

IotHubSasToken (com.microsoft.azure.sdk.iot.device.auth.IotHubSasToken)19 Test (org.junit.Test)15 DeviceClientConfig (com.microsoft.azure.sdk.iot.device.DeviceClientConfig)9 IotHubConnectionString (com.microsoft.azure.sdk.iot.device.IotHubConnectionString)9 NonStrictExpectations (mockit.NonStrictExpectations)6 IOException (java.io.IOException)5 AmqpsIotHubConnection (com.microsoft.azure.sdk.iot.device.transport.amqps.AmqpsIotHubConnection)3 MqttIotHubConnection (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttIotHubConnection)3 MqttMessaging (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttMessaging)3 URL (java.net.URL)3 Verifications (mockit.Verifications)3 MqttDeviceMethod (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceMethod)2 IotHubReactor (com.microsoft.azure.sdk.iot.device.transport.amqps.IotHubReactor)1 MqttDeviceTwin (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceTwin)1