Java源码示例:com.microsoft.aad.adal4j.ClientCredential

示例1
private AuthenticationResult acquireAccessTokenFromRefreshToken(String resource, String refreshToken) throws IOException {
    String authorityUrl = this.environment().activeDirectoryEndpoint() + this.domain();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    AuthenticationContext context = new AuthenticationContext(authorityUrl, false, executor);
    if (proxy() != null) {
        context.setProxy(proxy());
    }
    try {
        return context.acquireTokenByRefreshToken(refreshToken,
                new ClientCredential(applicationCredentials.clientId(), applicationCredentials.clientSecret()),
                resource, null).get();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        executor.shutdown();
    }
}
 
示例2
AuthenticationResult acquireNewAccessToken(String resource) throws IOException {
    if (authorizationCode == null) {
        throw new IllegalArgumentException("You must acquire an authorization code by redirecting to the authentication URL");
    }
    String authorityUrl = environment().activeDirectoryEndpoint() + domain();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    AuthenticationContext context = authenticationContextProvider.getAuthenticationContext(authorityUrl, false, executor);
    if (proxy() != null) {
        context.setProxy(proxy());
    }
    try {
        if (clientSecret != null) {
            return context.acquireTokenByAuthorizationCode(
                    authorizationCode,
                    new URI(redirectUrl),
                    new ClientCredential(applicationCredentials.clientId(), clientSecret),
                    resource, null).get();
        }
        throw new AuthenticationException("Please provide either a non-null secret.");
    } catch (URISyntaxException | InterruptedException | ExecutionException e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        executor.shutdown();
    }
}
 
示例3
@Test
public void testGetTokenWhenAuthenticationResultNotFoundForTheResourceButIsMRRTAndMultipleResourceRefreshTokenIsFalseThenGivenTokenShouldReturn()
        throws IOException, ExecutionException, InterruptedException {
    String customResource = "someOtherResourceWhichIsNotInTheTokensMap";

    Map<String, AuthenticationResult> tokens = Map.of(RESOURCE, new AuthenticationResult("type", ACCESS_TOKEN, REFRESH_TOKEN, PAST_DATE, "1",
            mock(UserInfo.class), false));

    String result = new CbDelegatedTokenCredentials(applicationTokenCredentials, REDIRECT_URL, tokens, CLIENT_SECRET, authenticationContextProvider,
            cbRefreshTokenClientProvider).getToken(customResource);

    assertEquals(ACCESS_TOKEN, result);

    verify(futureAuthenticationResult, times(0)).get();
    verify(applicationTokenCredentials, times(0)).clientId();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(format("%s/", DEFAULT_TEST_AD_ENDPOINT)));
    verify(authenticationContextProvider, times(0)).getAuthenticationContext(anyString(), anyBoolean(), any(ExecutorService.class));
    verify(cbRefreshTokenClient, times(0)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(authenticationContext, times(0)).acquireTokenByAuthorizationCode(anyString(), any(URI.class), any(ClientCredential.class), anyString(), any());
}
 
示例4
public AuthenticationResult getAccessToken(final String refreshToken) {
    final String authority = getAuthority() + getTenant() + "/";
    if (logger.isDebugEnabled()) {
        logger.debug("refreshToken: {}, authority: {}", refreshToken, authority);
    }
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        final AuthenticationContext context = new AuthenticationContext(authority, true, service);
        final Future<AuthenticationResult> future =
                context.acquireTokenByRefreshToken(refreshToken, new ClientCredential(getClientId(), getClientSecret()), null, null);
        final AuthenticationResult result = future.get(acquisitionTimeout, TimeUnit.MILLISECONDS);
        if (result == null) {
            throw new SsoLoginException("authentication result was null");
        }
        return result;
    } catch (final Exception e) {
        throw new SsoLoginException("Failed to get a token.", e);
    } finally {
        if (service != null) {
            service.shutdown();
        }
    }
}
 
示例5
protected AuthenticationResult getAccessToken(final AuthorizationCode authorizationCode, final String currentUri) {
    final String authority = getAuthority() + getTenant() + "/";
    final String authCode = authorizationCode.getValue();
    if (logger.isDebugEnabled()) {
        logger.debug("authCode: {}, authority: {}, uri: {}", authCode, authority, currentUri);
    }
    final ClientCredential credential = new ClientCredential(getClientId(), getClientSecret());
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        final AuthenticationContext context = new AuthenticationContext(authority, true, service);
        final Future<AuthenticationResult> future =
                context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, null);
        final AuthenticationResult result = future.get(acquisitionTimeout, TimeUnit.MILLISECONDS);
        if (result == null) {
            throw new SsoLoginException("authentication result was null");
        }
        return result;
    } catch (final Exception e) {
        throw new SsoLoginException("Failed to get a token.", e);
    } finally {
        if (service != null) {
            service.shutdown();
        }
    }
}
 
示例6
/**
 * Private helper method that gets the access token for the authorization and resource depending on which variables are supplied in the environment.
 *
 * @param authorization
 * @param resource
 * @return
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws MalformedURLException
 * @throws Exception
 */
private AuthenticationResult getAccessToken(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException {

    AuthenticationResult result = null;

    //Starts a service to fetch access token.
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        AuthenticationContext context = new AuthenticationContext(authorization, false, service);

        Future<AuthenticationResult> future = null;

        //Acquires token based on client ID and client secret.
        if (!StringUtils.isEmpty(this.clientSecret) && !StringUtils.isEmpty(this.clientId)) {
            ClientCredential credentials = new ClientCredential(this.clientId, this.clientSecret);
            future = context.acquireToken(resource, credentials, null);
        }

        result = future.get();
    } finally {
        service.shutdown();
    }

    if (result == null) {
        log.error("Failed to get authentication token for key vault.");
        throw new RuntimeException("Authentication results were null.");
    }
    return result;
}
 
示例7
/**
 * Private helper method that gets the access token for the authorization and resource depending on which variables are supplied in the environment.
 *
 * @param authorization
 * @param resource
 * @return
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws MalformedURLException
 * @throws Exception
 */
private AuthenticationResult getAccessToken(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException {

    AuthenticationResult result = null;

    //Starts a service to fetch access token.
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        AuthenticationContext context = new AuthenticationContext(authorization, false, service);

        Future<AuthenticationResult> future = null;

        //Acquires token based on client ID and client secret.
        if (!StringUtils.isEmpty(this.clientSecret) && !StringUtils.isEmpty(this.clientId)) {
            ClientCredential credentials = new ClientCredential(this.clientId, this.clientSecret);
            future = context.acquireToken(resource, credentials, null);
        }

        result = future.get();
    } finally {
        service.shutdown();
    }

    if (result == null) {
        log.error("Failed to get authentication token for key vault.");
        throw new RuntimeException("Authentication results were null.");
    }
    return result;
}
 
示例8
/**
 * Private helper method that gets the access token for the authorization and resource depending on which variables are supplied in the environment.
 *
 * @param authorization
 * @param resource
 * @return
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws MalformedURLException
 * @throws Exception
 */
private AuthenticationResult getAccessToken(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException {

    AuthenticationResult result = null;

    //Starts a service to fetch access token.
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        AuthenticationContext context = new AuthenticationContext(authorization, false, service);

        Future<AuthenticationResult> future = null;

        //Acquires token based on client ID and client secret.
        if (!StringUtils.isEmpty(this.clientSecret) && !StringUtils.isEmpty(this.clientId)) {
            ClientCredential credentials = new ClientCredential(this.clientId, this.clientSecret);
            future = context.acquireToken(resource, credentials, null);
        }

        result = future.get();
    } finally {
        service.shutdown();
    }

    if (result == null) {
        log.error("Failed to get authentication token for key vault.");
        throw new RuntimeException("Authentication results were null.");
    }
    return result;
}
 
示例9
/**
 * Private helper method that gets the access token for the authorization and resource depending on which variables are supplied in the environment.
 *
 * @param authorization
 * @param resource
 * @return
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws MalformedURLException
 * @throws Exception
 */
private AuthenticationResult getAccessToken(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException {

    AuthenticationResult result = null;

    //Starts a service to fetch access token.
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        AuthenticationContext context = new AuthenticationContext(authorization, false, service);

        Future<AuthenticationResult> future = null;

        //Acquires token based on client ID and client secret.
        if (!StringUtils.isEmpty(this.clientSecret) && !StringUtils.isEmpty(this.clientId)) {
            ClientCredential credentials = new ClientCredential(this.clientId, this.clientSecret);
            future = context.acquireToken(resource, credentials, null);
        }

        result = future.get();
    } finally {
        service.shutdown();
    }

    if (result == null) {
        log.error("Failed to get authentication token for key vault.");
        throw new RuntimeException("Authentication results were null.");
    }
    return result;
}
 
示例10
@Test
public void getCredentialsUsingInjectedParameters() throws Exception {
    Future<AuthenticationResult> response = mock(Future.class);

    AuthenticationResult authenticationResult = new AuthenticationResult(null,"accessToken",null,0L,null,null,false);

    when(response.get()).thenReturn(authenticationResult);
    when(authenticationContext.acquireToken(anyString(), any(ClientCredential.class), any())).thenReturn(response);

    String result = credentials.doAuthenticate("auth","resource",null);

    assertThat(result).isEqualTo("accessToken");
    verify(authenticationContext).acquireToken(anyString(), any(ClientCredential.class), any());
    Mockito.verifyNoMoreInteractions(authenticationContext);
}
 
示例11
@Test(expected = RuntimeException.class)
public void ifFutureAbortsThenExecutionExceptionThrownAsRuntimeException() throws ExecutionException, InterruptedException {
    Future<AuthenticationResult> response = mock(Future.class);
    when(response.get()).thenThrow(ExecutionException.class);
    when(authenticationContext.acquireToken(anyString(), any(ClientCredential.class), any())).thenReturn(response);

    credentials.doAuthenticate("auth", "resource", null);
}
 
示例12
@Test(expected = RuntimeException.class)
public void threadInterruptedExceptionIsCaughtAndLogged() throws ExecutionException, InterruptedException {
    Future<AuthenticationResult> response = mock(Future.class);
    when(response.get()).thenThrow(InterruptedException.class);
    when(authenticationContext.acquireToken(anyString(), any(ClientCredential.class), any())).thenReturn(response);

    credentials.doAuthenticate("auth", "resource", null);
}
 
示例13
public AzureOAuthTokenProvider(String oauthUrl, String clientId, String clientSecret) throws IOException {
  try {
    authContext = new AuthenticationContext(oauthUrl, true,
      Executors.newCachedThreadPool(new NamedThreadFactory("adls-oauth-request")));
    credential = new ClientCredential(clientId, clientSecret);
    authResult = requestNewToken();
  } catch (IOException ioe) {
    throw ioe;
  } catch (Exception e) {
    throw new IOException(e);
  }
}
 
示例14
private AuthenticationResult getAccessToken(VertxContext<Server> vertxContext, String clientId, String clientKey, String authorization, String resource) throws Exception {
    AuthenticationContext context = new AuthenticationContext(authorization, false, executorService);
    ClientCredential credentials = new ClientCredential(clientId, clientKey);
    AuthenticationResult result = context.acquireToken(resource, credentials, null).get();
    checkNotNull(result, "AuthenticationResult was null");
    return result;
}
 
示例15
private AuthenticationResult acquireAccessToken(String resource) throws IOException {
    String authorityUrl = this.environment().activeDirectoryEndpoint() + this.domain();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    AuthenticationContext context = new AuthenticationContext(authorityUrl, false, executor);
    if (proxy() != null) {
        context.setProxy(proxy());
    }
    if (sslSocketFactory() != null) {
        context.setSslSocketFactory(sslSocketFactory());
    }
    try {
        if (clientSecret != null) {
            return context.acquireToken(
                    resource,
                    new ClientCredential(this.clientId(), clientSecret),
                    null).get();
        } else if (clientCertificate != null && clientCertificatePassword != null) {
            return context.acquireToken(
                    resource,
                    AsymmetricKeyCredential.create(clientId, new ByteArrayInputStream(clientCertificate), clientCertificatePassword),
                    null).get();
        } else if (clientCertificate != null) {
            return context.acquireToken(
                    resource,
                    AsymmetricKeyCredential.create(clientId(), privateKeyFromPem(new String(clientCertificate)), publicKeyFromPem(new String(clientCertificate))),
                    null).get();
        }
        throw new AuthenticationException("Please provide either a non-null secret or a non-null certificate.");
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        executor.shutdown();
    }
}
 
示例16
@NotNull
public static AuthenticationResult getToken(@NotNull final AuthorizationTokenInputs inputs) throws Exception {
    final ExecutorService service = Executors.newSingleThreadExecutor();
    final AuthenticationContext context = new AuthenticationContext(inputs.getAuthority(), false, service);
    context.setProxy(getProxy(inputs.getProxyHost(), inputs.getProxyPort(), inputs.getProxyUsername(), inputs.getProxyPassword()));

    //Verifying if loginType is API to instantiate ClientCredential object
    if (inputs.getLoginType().equalsIgnoreCase(API)) {
        final ClientCredential credential = new ClientCredential(inputs.getClientId(), inputs.getClientSecret());
        return acquireToken(context, inputs, credential, service);
    }

    //Otherwise, the loginType is Native since the verification was already made in the @Action
    return acquireToken(context, inputs, service);
}
 
示例17
@Test
public void testGetTokenClientSecretAndAuthorizationCodeGivenThroughConstructorThenNewAccessTokenReturns() throws IOException, ExecutionException,
                InterruptedException {
    String customAccessToken = "customAccessToken";
    String authorityUrl = format("%s/%s", format(TEST_AD_ENDPOINT, HTTPS), TEST_DOMAIN);
    AuthenticationResult authenticationResult = new AuthenticationResult("type", customAccessToken, REFRESH_TOKEN, 123456789L, "1", mock(UserInfo.class),
            true);
    when(applicationTokenCredentials.clientId()).thenReturn(CLIENT_ID);
    when(authenticationContextProvider.getAuthenticationContext(eq(authorityUrl), eq(false),
            any(ExecutorService.class))).thenReturn(authenticationContext);
    when(authenticationContext.acquireTokenByAuthorizationCode(eq(AUTHORIZATION_CODE), any(URI.class), any(ClientCredential.class), eq(RESOURCE), eq(null)))
            .thenReturn(futureAuthenticationResult);
    when(futureAuthenticationResult.get()).thenReturn(authenticationResult);

    String result = new CbDelegatedTokenCredentials(applicationTokenCredentials, REDIRECT_URL, AUTHORIZATION_CODE, CLIENT_SECRET,
            authenticationContextProvider, cbRefreshTokenClientProvider).getToken(RESOURCE);

    Assert.assertNotEquals(ACCESS_TOKEN, result);
    assertEquals(customAccessToken, result);

    verify(futureAuthenticationResult, times(1)).get();
    verify(applicationTokenCredentials, times(1)).clientId();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(format("%s/", DEFAULT_TEST_AD_ENDPOINT)));
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(anyString(), anyBoolean(), any(ExecutorService.class));
    verify(cbRefreshTokenClient, times(0)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(eq(authorityUrl), eq(false), any(ExecutorService.class));
    verify(authenticationContext, times(1)).acquireTokenByAuthorizationCode(anyString(), any(URI.class), any(ClientCredential.class), anyString(), any());
    verify(authenticationContext, times(1)).acquireTokenByAuthorizationCode(eq(AUTHORIZATION_CODE), any(URI.class), any(ClientCredential.class),
            eq(RESOURCE), eq(null));
}
 
示例18
@Test
public void testAcquireNewAccessTokenWhenAuthenticationResultGetFailsDueToExecutionExceptionThenIOExceptionComes() throws IOException, ExecutionException,
        InterruptedException {
    String authorityUrl = format("%s/%s", format(TEST_AD_ENDPOINT, HTTPS), TEST_DOMAIN);
    when(applicationTokenCredentials.clientId()).thenReturn(CLIENT_ID);
    when(authenticationContextProvider.getAuthenticationContext(eq(authorityUrl), eq(false),
            any(ExecutorService.class))).thenReturn(authenticationContext);
    when(authenticationContext.acquireTokenByAuthorizationCode(eq(AUTHORIZATION_CODE), any(URI.class), any(ClientCredential.class), eq(RESOURCE), eq(null)))
            .thenReturn(futureAuthenticationResult);
    doThrow(new ExecutionException("some execution failure", new RuntimeException())).when(futureAuthenticationResult).get();

    thrown.expect(IOException.class);
    thrown.expectMessage("some execution failure");


    new CbDelegatedTokenCredentials(applicationTokenCredentials, REDIRECT_URL, AUTHORIZATION_CODE, CLIENT_SECRET,
            authenticationContextProvider, cbRefreshTokenClientProvider).acquireNewAccessToken(RESOURCE);

    verify(futureAuthenticationResult, times(1)).get();
    verify(applicationTokenCredentials, times(1)).clientId();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(format("%s/", DEFAULT_TEST_AD_ENDPOINT)));
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(anyString(), anyBoolean(), any(ExecutorService.class));
    verify(cbRefreshTokenClient, times(0)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(eq(authorityUrl), eq(false), any(ExecutorService.class));
    verify(authenticationContext, times(1)).acquireTokenByAuthorizationCode(anyString(), any(URI.class), any(ClientCredential.class), anyString(), any());
    verify(authenticationContext, times(1)).acquireTokenByAuthorizationCode(eq(AUTHORIZATION_CODE), any(URI.class), any(ClientCredential.class),
            eq(RESOURCE), eq(null));
}
 
示例19
@Test
public void testAcquireNewAccessTokenWhenAuthenticationResultGetFailsDueToInterruptedExceptionThenIOExceptionComes() throws IOException, ExecutionException,
        InterruptedException {
    String authorityUrl = format("%s/%s", format(TEST_AD_ENDPOINT, HTTPS), TEST_DOMAIN);
    when(applicationTokenCredentials.clientId()).thenReturn(CLIENT_ID);
    when(authenticationContextProvider.getAuthenticationContext(eq(authorityUrl), eq(false),
            any(ExecutorService.class))).thenReturn(authenticationContext);
    when(authenticationContext.acquireTokenByAuthorizationCode(eq(AUTHORIZATION_CODE), any(URI.class), any(ClientCredential.class), eq(RESOURCE), eq(null)))
            .thenReturn(futureAuthenticationResult);
    doThrow(new InterruptedException("some interrupted me!")).when(futureAuthenticationResult).get();

    thrown.expect(IOException.class);
    thrown.expectMessage("some interrupted me!");


    new CbDelegatedTokenCredentials(applicationTokenCredentials, REDIRECT_URL, AUTHORIZATION_CODE, CLIENT_SECRET,
            authenticationContextProvider, cbRefreshTokenClientProvider).acquireNewAccessToken(RESOURCE);

    verify(futureAuthenticationResult, times(1)).get();
    verify(applicationTokenCredentials, times(1)).clientId();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(format("%s/", DEFAULT_TEST_AD_ENDPOINT)));
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(anyString(), anyBoolean(), any(ExecutorService.class));
    verify(cbRefreshTokenClient, times(0)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(eq(authorityUrl), eq(false), any(ExecutorService.class));
    verify(authenticationContext, times(1)).acquireTokenByAuthorizationCode(anyString(), any(URI.class), any(ClientCredential.class), anyString(), any());
    verify(authenticationContext, times(1)).acquireTokenByAuthorizationCode(eq(AUTHORIZATION_CODE), any(URI.class), any(ClientCredential.class),
            eq(RESOURCE), eq(null));
}
 
示例20
@Test
public void testGetTokenWhenDifferentResourceGivenThanProvidedInTokensAndShouldRefreshThenNewAccessTokenReturnsAfterwards()
                throws IOException, ExecutionException, InterruptedException {
    String expected = "someOtherAccessToken";
    String customResource = "someOtherResourceWhichIsNotInTheTokensMap";

    Map<String, AuthenticationResult> tokens = Map.of(RESOURCE, new AuthenticationResult("type", ACCESS_TOKEN, REFRESH_TOKEN, PAST_DATE,
            "1", mock(UserInfo.class),
            true));

    AuthenticationResult refreshTokenFromAccessTokenResult = new AuthenticationResult("type", expected, REFRESH_TOKEN,
            PAST_DATE, "2", userInfo, true);

    when(cbRefreshTokenClientProvider.getCBRefreshTokenClient(eq(String.format("%s/", DEFAULT_TEST_AD_ENDPOINT)))).thenReturn(cbRefreshTokenClient);
    when(cbRefreshTokenClient.refreshToken(TEST_DOMAIN, CLIENT_ID, CLIENT_SECRET, customResource, REFRESH_TOKEN, MULTIPLE_RESOURCE_REFRESH_TOKEN))
            .thenReturn(refreshTokenFromAccessTokenResult);
    when(applicationTokenCredentials.clientId()).thenReturn(CLIENT_ID);

    String result = new CbDelegatedTokenCredentials(applicationTokenCredentials, REDIRECT_URL, tokens, CLIENT_SECRET, authenticationContextProvider,
            cbRefreshTokenClientProvider)
            .getToken(customResource);

    assertEquals(expected, result);

    verify(futureAuthenticationResult, times(0)).get();
    verify(applicationTokenCredentials, times(1)).clientId();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(format("%s/", DEFAULT_TEST_AD_ENDPOINT)));
    verify(authenticationContextProvider, times(0)).getAuthenticationContext(anyString(), anyBoolean(), any(ExecutorService.class));
    verify(cbRefreshTokenClient, times(1)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(authenticationContext, times(0)).acquireTokenByAuthorizationCode(anyString(), any(URI.class), any(ClientCredential.class), anyString(), any());
    verify(cbRefreshTokenClient, times(1)).refreshToken(TEST_DOMAIN, CLIENT_ID, CLIENT_SECRET, customResource, REFRESH_TOKEN,
            MULTIPLE_RESOURCE_REFRESH_TOKEN);
}
 
示例21
@Test
public void testGetTokenWhenDifferentResourceGivenThanProvidedInTokensAndShouldRefreshAndRefreshingTokenFailsThenAuthenticationExceptionComes()
                throws IOException, ExecutionException, InterruptedException {
    String customResource = "someOtherResourceWhichIsNotInTheTokensMap";

    Map<String, AuthenticationResult> tokens = Map.of(RESOURCE, new AuthenticationResult("type", ACCESS_TOKEN, REFRESH_TOKEN, PAST_DATE,
            "1", mock(UserInfo.class),
            true));

    when(cbRefreshTokenClientProvider.getCBRefreshTokenClient(eq(String.format("%s/", DEFAULT_TEST_AD_ENDPOINT)))).thenReturn(cbRefreshTokenClient);
    doThrow(new RuntimeException()).when(cbRefreshTokenClient).refreshToken(TEST_DOMAIN, CLIENT_ID, CLIENT_SECRET, customResource, REFRESH_TOKEN,
            MULTIPLE_RESOURCE_REFRESH_TOKEN);
    when(applicationTokenCredentials.clientId()).thenReturn(CLIENT_ID);

    thrown.expect(AuthenticationException.class);
    thrown.expectMessage("Could not obtain refresh token.");

    new CbDelegatedTokenCredentials(applicationTokenCredentials, REDIRECT_URL, tokens, CLIENT_SECRET, authenticationContextProvider,
            cbRefreshTokenClientProvider)
            .getToken(customResource);

    verify(futureAuthenticationResult, times(0)).get();
    verify(applicationTokenCredentials, times(1)).clientId();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClient, times(1)).refreshToken(TEST_DOMAIN, CLIENT_ID, CLIENT_SECRET, customResource, REFRESH_TOKEN,
            MULTIPLE_RESOURCE_REFRESH_TOKEN);
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(format("%s/", DEFAULT_TEST_AD_ENDPOINT)));
    verify(authenticationContextProvider, times(0)).getAuthenticationContext(anyString(), anyBoolean(), any(ExecutorService.class));
    verify(cbRefreshTokenClient, times(1)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(authenticationContext, times(0)).acquireTokenByAuthorizationCode(anyString(), any(URI.class), any(ClientCredential.class), anyString(), any());
}
 
示例22
private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception {

        String clientId = System.getenv("arm.clientid");

        if (clientId == null) {
            throw new Exception("Please inform arm.clientid in the environment settings.");
        }

        String clientKey = System.getenv("arm.clientkey");
        String username = System.getenv("arm.username");
        String password = System.getenv("arm.password");

        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            AuthenticationContext context = new AuthenticationContext(authorization, false, service);

            Future<AuthenticationResult> future = null;

            if (clientKey != null && password == null) {
                ClientCredential credentials = new ClientCredential(clientId, clientKey);
                future = context.acquireToken(resource, credentials, null);
            }

            if (password != null && clientKey == null) {
                future = context.acquireToken(resource, clientId, username, password, null);
            }

            if (future == null) {
                throw new Exception(
                        "Missing or ambiguous credentials - please inform exactly one of arm.clientkey or arm.password in the environment settings.");
            }

            result = future.get();
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new RuntimeException("authentication result was null");
        }
        return result;
    }
 
示例23
private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception {

		String clientId = System.getenv("arm.clientid");

		if (clientId == null) {
			throw new Exception("Please inform arm.clientid in the environment settings.");
		}

		String clientKey = System.getenv("arm.clientkey");
		String username = System.getenv("arm.username");
		String password = System.getenv("arm.password");

		AuthenticationResult result = null;
		ExecutorService service = null;
		try {
			service = Executors.newFixedThreadPool(1);
			AuthenticationContext context = new AuthenticationContext(authorization, false, service);

			Future<AuthenticationResult> future = null;

			if (clientKey != null && password == null) {
				ClientCredential credentials = new ClientCredential(clientId, clientKey);
				future = context.acquireToken(resource, credentials, null);
			}

			if (password != null && clientKey == null) {
				future = context.acquireToken(resource, clientId, username, password, null);
			}

			if (future == null) {
				throw new Exception(
						"Missing or ambiguous credentials - please inform exactly one of arm.clientkey or arm.password in the environment settings.");
			}

			result = future.get();
		} finally {
			service.shutdown();
		}

		if (result == null) {
			throw new RuntimeException("authentication result was null");
		}
		return result;
	}
 
示例24
private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception {

		String clientId = System.getenv("arm.clientid");

		if (clientId == null) {
			throw new Exception("Please inform arm.clientid in the environment settings.");
		}

		String clientKey = System.getenv("arm.clientkey");
		String username = System.getenv("arm.username");
		String password = System.getenv("arm.password");

		AuthenticationResult result = null;
		ExecutorService service = null;
		try {
			service = Executors.newFixedThreadPool(1);
			AuthenticationContext context = new AuthenticationContext(authorization, false, service);

			Future<AuthenticationResult> future = null;

			if (clientKey != null && password == null) {
				ClientCredential credentials = new ClientCredential(clientId, clientKey);
				future = context.acquireToken(resource, credentials, null);
			}

			if (password != null && clientKey == null) {
				future = context.acquireToken(resource, clientId, username, password, null);
			}

			if (future == null) {
				throw new Exception(
						"Missing or ambiguous credentials - please inform exactly one of arm.clientkey or arm.password in the environment settings.");
			}

			result = future.get();
		} finally {
			service.shutdown();
		}

		if (result == null) {
			throw new RuntimeException("authentication result was null");
		}
		return result;
	}
 
示例25
AuthenticationResult acquireNewAccessToken(String resource) throws IOException {
    if (authorizationCode == null) {
        throw new IllegalArgumentException("You must acquire an authorization code by redirecting to the authentication URL");
    }
    String authorityUrl = this.environment().activeDirectoryEndpoint() + this.domain();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    AuthenticationContext context = new AuthenticationContext(authorityUrl, false, executor);
    if (proxy() != null) {
        context.setProxy(proxy());
    }
    try {
        if (applicationCredentials.clientSecret() != null) {
            return context.acquireTokenByAuthorizationCode(
                    authorizationCode,
                    new URI(redirectUrl),
                    new ClientCredential(applicationCredentials.clientId(), applicationCredentials.clientSecret()),
                    resource, null).get();
        } else if (applicationCredentials.clientCertificate() != null && applicationCredentials.clientCertificatePassword() != null) {
            return context.acquireTokenByAuthorizationCode(
                    authorizationCode,
                    new URI(redirectUrl),
                    AsymmetricKeyCredential.create(
                            applicationCredentials.clientId(),
                            new ByteArrayInputStream(applicationCredentials.clientCertificate()),
                            applicationCredentials.clientCertificatePassword()),
                    resource,
                    null).get();
        } else if (applicationCredentials.clientCertificate() != null) {
            return context.acquireTokenByAuthorizationCode(
                    authorizationCode,
                    new URI(redirectUrl),
                    AsymmetricKeyCredential.create(
                            clientId(),
                            ApplicationTokenCredentials.privateKeyFromPem(new String(applicationCredentials.clientCertificate())),
                            ApplicationTokenCredentials.publicKeyFromPem(new String(applicationCredentials.clientCertificate()))),
                    resource,
                    null).get();
        }
        throw new AuthenticationException("Please provide either a non-null secret or a non-null certificate.");
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        executor.shutdown();
    }
}
 
示例26
@NotNull
private static AuthenticationResult acquireToken(@NotNull final AuthenticationContext context, @NotNull final AuthorizationTokenInputs inputs, @NotNull ClientCredential credential, @NotNull ExecutorService service) throws Exception {
    final Future<AuthenticationResult> future = context.acquireToken(inputs.getResource(), credential, null);
    service.shutdown();
    return future.get();
}