Search in sources :

Example 1 with AccessToken

use of com.azure.core.credential.AccessToken in project azure-iot-sdk-java by Azure.

the class TokenCredentialCacheTest method tokenCredentialRenewsExpiredToken.

@Test
public void tokenCredentialRenewsExpiredToken() {
    TokenCredentialCache cache = new TokenCredentialCache(mockTokenCredential);
    new Expectations() {

        {
            mockTokenCredential.getToken((TokenRequestContext) any).block();
            result = mockAccessToken;
            mockAccessToken.getExpiresAt();
            result = OffsetDateTime.MAX;
        }
    };
    AccessToken accessToken = cache.getAccessToken();
    // Token expired one minute ago
    final long milliseconds = System.currentTimeMillis() - (60 * 1000);
    new Expectations() {

        {
            mockAccessToken.getExpiresAt();
            result = Instant.ofEpochMilli(milliseconds).atOffset(ZoneOffset.UTC);
            mockTokenCredential.getToken((TokenRequestContext) any).block();
            result = mockAccessToken2;
        }
    };
    // act
    AccessToken accessToken2 = cache.getAccessToken();
    // assert
    assertEquals(mockAccessToken, accessToken);
    assertEquals(mockAccessToken2, accessToken2);
}
Also used : Expectations(mockit.Expectations) TokenRequestContext(com.azure.core.credential.TokenRequestContext) AccessToken(com.azure.core.credential.AccessToken) TokenCredentialCache(com.microsoft.azure.sdk.iot.service.auth.TokenCredentialCache) Test(org.junit.Test)

Example 2 with AccessToken

use of com.azure.core.credential.AccessToken in project azure-iot-sdk-java by Azure.

the class TokenCredentialCacheTest method tokenCredentialDoesNotRenewTooProactively.

@Test
public void tokenCredentialDoesNotRenewTooProactively() {
    TokenCredentialCache cache = new TokenCredentialCache(mockTokenCredential);
    new Expectations() {

        {
            mockTokenCredential.getToken((TokenRequestContext) any).block();
            result = mockAccessToken;
            mockAccessToken.getExpiresAt();
            result = OffsetDateTime.MAX;
        }
    };
    AccessToken accessToken = cache.getAccessToken();
    // 12 minutes from the current time, should not fit within the proactive renewal range, so the cached token shouldn't be renewed
    final long milliseconds = System.currentTimeMillis() + (12 * 60 * 1000);
    new Expectations() {

        {
            mockAccessToken.getExpiresAt();
            result = Instant.ofEpochMilli(milliseconds).atOffset(ZoneOffset.UTC);
        }
    };
    // act
    AccessToken accessToken2 = cache.getAccessToken();
    // assert
    assertEquals(mockAccessToken, accessToken);
    assertEquals(mockAccessToken, accessToken2);
}
Also used : Expectations(mockit.Expectations) TokenRequestContext(com.azure.core.credential.TokenRequestContext) AccessToken(com.azure.core.credential.AccessToken) TokenCredentialCache(com.microsoft.azure.sdk.iot.service.auth.TokenCredentialCache) Test(org.junit.Test)

Example 3 with AccessToken

use of com.azure.core.credential.AccessToken in project azure-iot-sdk-java by Azure.

the class TokenCredentialCacheTest method tokenCredentialProactivelyRenewsToken.

@Test
public void tokenCredentialProactivelyRenewsToken() {
    TokenCredentialCache cache = new TokenCredentialCache(mockTokenCredential);
    new Expectations() {

        {
            mockTokenCredential.getToken((TokenRequestContext) any).block();
            result = mockAccessToken;
            mockAccessToken.getExpiresAt();
            result = OffsetDateTime.MAX;
        }
    };
    AccessToken accessToken = cache.getAccessToken();
    // 8 minutes from the current time, should fit within the proactive renewal range
    final long milliseconds = System.currentTimeMillis() + (8 * 60 * 1000);
    new Expectations() {

        {
            mockAccessToken.getExpiresAt();
            result = Instant.ofEpochMilli(milliseconds).atOffset(ZoneOffset.UTC);
            mockTokenCredential.getToken((TokenRequestContext) any).block();
            result = mockAccessToken2;
        }
    };
    // act
    AccessToken accessToken2 = cache.getAccessToken();
    // assert
    assertEquals(mockAccessToken, accessToken);
    assertEquals(mockAccessToken2, accessToken2);
}
Also used : Expectations(mockit.Expectations) TokenRequestContext(com.azure.core.credential.TokenRequestContext) AccessToken(com.azure.core.credential.AccessToken) TokenCredentialCache(com.microsoft.azure.sdk.iot.service.auth.TokenCredentialCache) Test(org.junit.Test)

Example 4 with AccessToken

use of com.azure.core.credential.AccessToken in project azure-iot-sdk-java by Azure.

the class CbsSessionHandler method authenticate.

private void authenticate() {
    UUID authenticationMessageCorrelationId = UUID.randomUUID();
    this.cbsReceiverLinkHandler.setAuthenticationMessageCorrelationId(authenticationMessageCorrelationId);
    int authenticationMessageDeliveryTag = this.cbsSenderLinkHandler.sendAuthenticationMessage(authenticationMessageCorrelationId);
    AccessToken currentAccessToken = this.cbsSenderLinkHandler.getCurrentAccessToken();
    if (authenticationMessageDeliveryTag == -1) {
        log.error("Failed to send authentication message");
    } else {
        log.debug("Successfully sent authentication message");
    }
    // Connection only proactively renews when a token provider is present
    if (this.credential != null || this.sasTokenProvider != null) {
        // Each execution of onTimerTask is responsible for scheduling the next occurrence based on how long the previous token is valid for
        OffsetDateTime currentOffsetDateTime = OffsetDateTime.now();
        OffsetDateTime tokenExpiryOffsetDateTime = currentAccessToken.getExpiresAt();
        Duration diff = Duration.between(tokenExpiryOffsetDateTime, currentOffsetDateTime).abs();
        long millisecondsToTokenExpiry = diff.toMillis();
        // Cast of double to int here is safe because this value does not need to be precisely 85% of the token renewal time
        // so it is okay to truncate this double to its int value
        double proactiveTokenRenewalMillis = (millisecondsToTokenExpiry * TOKEN_RENEWAL_PERCENT);
        if (proactiveTokenRenewalMillis >= Integer.MAX_VALUE) {
            // To avoid overflow issues, don't try to schedule any further in the future than Integer.MAX_VALUE
            scheduleProactiveRenewal(Integer.MAX_VALUE);
        } else {
            // Safe cast since we don't need to preserve the precision of the double, we just need to be at roughly 85% of
            // the token's lifespan
            scheduleProactiveRenewal((int) (proactiveTokenRenewalMillis));
        }
    }
}
Also used : OffsetDateTime(java.time.OffsetDateTime) AccessToken(com.azure.core.credential.AccessToken) Duration(java.time.Duration) UUID(java.util.UUID)

Example 5 with AccessToken

use of com.azure.core.credential.AccessToken in project azure-iot-sdk-java by Azure.

the class CbsSenderLinkHandler method getAccessTokenFromSasToken.

private AccessToken getAccessTokenFromSasToken(String sasToken) {
    // split "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s" into "SharedAccessSignature" "sr=%s&sig=%s&se=%s&skn=%s"
    String[] signatureParts = sasToken.split(" ");
    if (signatureParts.length != 2) {
        RuntimeException runtimeException = new RuntimeException("failed to parse shared access signature, unable to get the signature's time to live");
        log.error("Failed to get token from AzureSasCredential", runtimeException);
        throw runtimeException;
    }
    // split "sr=%s&sig=%s&se=%s&skn=%s" into "sr=%s" "sig=%s" "se=%s" "skn=%s"
    String[] signatureKeyValuePairs = signatureParts[1].split("&");
    int expiryTimeSeconds = -1;
    for (String signatureKeyValuePair : signatureKeyValuePairs) {
        if (signatureKeyValuePair.startsWith(EXPIRY_KEY)) {
            // substring "se=%s" into "%s"
            String expiryTimeValue = signatureKeyValuePair.substring(EXPIRY_KEY.length());
            try {
                expiryTimeSeconds = Integer.parseInt(expiryTimeValue);
            } catch (NumberFormatException e) {
                RuntimeException runtimeException = new RuntimeException("Failed to parse shared access signature, unable to parse the signature's time to live to an integer", e);
                log.error("Failed to get token from AzureSasCredential", runtimeException);
                throw runtimeException;
            }
        }
    }
    if (expiryTimeSeconds == -1) {
        RuntimeException runtimeException = new RuntimeException("Failed to parse shared access signature, signature does not include key value pair for expiry time");
        log.error("Failed to get token from AzureSasCredential", runtimeException);
        throw runtimeException;
    }
    OffsetDateTime sasTokenExpiryOffsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(expiryTimeSeconds), ZoneId.systemDefault());
    return new AccessToken(sasToken, sasTokenExpiryOffsetDateTime);
}
Also used : OffsetDateTime(java.time.OffsetDateTime) AccessToken(com.azure.core.credential.AccessToken)

Aggregations

AccessToken (com.azure.core.credential.AccessToken)7 TokenRequestContext (com.azure.core.credential.TokenRequestContext)4 TokenCredentialCache (com.microsoft.azure.sdk.iot.service.auth.TokenCredentialCache)4 Expectations (mockit.Expectations)4 Test (org.junit.Test)4 OffsetDateTime (java.time.OffsetDateTime)2 IAuthenticationResult (com.microsoft.aad.msal4j.IAuthenticationResult)1 Duration (java.time.Duration)1 UUID (java.util.UUID)1