com.microsoft.aad.adal4j.AuthenticationContext Java Examples

The following examples show how to use com.microsoft.aad.adal4j.AuthenticationContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
AuthenticationResult acquireNewAccessToken(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());
    }
    try {
        return context.acquireToken(
                resource,
                this.clientId(),
                this.username(),
                this.password,
                null).get();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        executor.shutdown();
    }
}
 
Example #2
Source File: AzureAdAuthenticator.java    From fess with Apache License 2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #3
Source File: AzureAdAuthenticator.java    From fess with Apache License 2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #4
Source File: CbDelegatedTokenCredentials.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #5
Source File: Office365Authenticator.java    From powerbi-rest-java with MIT License 6 votes vote down vote up
private String _authenticate() throws AuthenticationFailureException {
    try {
        AuthenticationContext authenticationContext = new AuthenticationContext(
                authority,
                validateAuthority,
                executor
        );

        String result = getAccessToken(
                authenticationContext,
                powerBiResourceId,
                nativeClientId,
                username + "@" + tenant,
                password
        );

        if (StringUtils.isEmpty(result)) {
            throw new AuthenticationFailureException("Returned access token is null.");
        }

        return result;
    } catch (ExecutionException | InterruptedException | IOException e) {
        throw new AuthenticationFailureException(e);
    }
}
 
Example #6
Source File: DelegatedTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
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();
    }
}
 
Example #7
Source File: UserTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
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, this.clientId(),
                resource, null).get();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        executor.shutdown();
    }
}
 
Example #8
Source File: ITManagedStorageAccountKey.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static AuthenticationResult getAccessToken(String authorization, String resource) throws Exception {
    AuthenticationResult result = null;
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        AuthenticationContext context = new AuthenticationContext(authorization, false, service);
        Future<AuthenticationResult> future = null;
        future = context.acquireToken(resource, CLIENT_ID, MSAK_USER, MSAK_PASSWORD, null);
        result = future.get();
    } finally {
        service.shutdown();
    }

    if (result == null) {
        throw new RuntimeException("authentication result was null");
    }
    return result;
}
 
Example #9
Source File: AzureActiveDirectoryAuthenticator.java    From java with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> refresh(Map<String, Object> config) {
  // TODO: Support national clouds!
  String cloud = "https://login.microsoftonline.com";
  String tenantId = (String) config.get(TENANT_ID);
  String authority = cloud + "/" + tenantId;
  String clientId = (String) config.get(CLIENT_ID);
  String refreshToken = (String) config.get(REFRESH_TOKEN);

  try {
    AuthenticationContext context =
        new AuthenticationContext(authority, true, Executors.newSingleThreadExecutor());
    Future<AuthenticationResult> resultFuture =
        context.acquireTokenByRefreshToken(refreshToken, clientId, null);
    AuthenticationResult result = resultFuture.get();
    config.put(ACCESS_TOKEN, result.getAccessToken());
    config.put(REFRESH_TOKEN, result.getRefreshToken());

    return config;

  } catch (InterruptedException | MalformedURLException | ExecutionException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #10
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: AzureOAuthTokenProvider.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example #13
Source File: AzureKms.java    From sfs with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: ApplicationTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
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();
    }
}
 
Example #15
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: AzureKeyVaultClientCredentialsTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Before
public void onSetUp() {
    executorService = mock(ExecutorService.class);
    authenticationContext = mock(AuthenticationContext.class);
    credentials = new AzureKeyVaultClientCredentials("clientId","clientSecret", executorService);
    credentials.setAuthenticationContext(authenticationContext);
}
 
Example #17
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: Office365Authenticator.java    From powerbi-rest-java with MIT License 5 votes vote down vote up
private String getAccessToken(AuthenticationContext authenticationContext, String resourceId, String clientId,
                              String username, String password) throws ExecutionException, InterruptedException {
    return authenticationContext.acquireToken(
            resourceId,
            clientId,
            username,
            password,
            null
    ).get().getAccessToken();
}
 
Example #19
Source File: AuthorizationTokenImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@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()));
    final Future<AuthenticationResult> future = context.acquireToken(inputs.getResource(), inputs.getClientId(), inputs.getUsername(), inputs.getPassword(), null);
    service.shutdown();
    return future.get();
}
 
Example #20
Source File: AuthorizationTokenImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #21
Source File: AzureKeyVaultClientCredentials.java    From tessera with Apache License 2.0 4 votes vote down vote up
void setAuthenticationContext(AuthenticationContext authenticationContext) {
    this.authenticationContext = authenticationContext;
}
 
Example #22
Source File: AuthenticationContextProvider.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public AuthenticationContext getAuthenticationContext(@NotNull String authority, boolean validateAuthority, @NotNull ExecutorService service)
                throws MalformedURLException {
    return new AuthenticationContext(authority, validateAuthority, service);
}
 
Example #23
Source File: AuthorizationTokenImpl.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
@NotNull
private static AuthenticationResult acquireToken(@NotNull final AuthenticationContext context, @NotNull final AuthorizationTokenInputs inputs, @NotNull ExecutorService service) throws Exception {
    final Future<AuthenticationResult> future = context.acquireToken(inputs.getResource(), inputs.getClientId(), inputs.getUsername(), inputs.getPassword(), null);
    service.shutdown();
    return future.get();
}
 
Example #24
Source File: AuthorizationTokenImpl.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example #25
Source File: KeyVaultClientIntegrationTestBase.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
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;
	}
 
Example #26
Source File: DelegatedTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
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();
    }
}
 
Example #27
Source File: KeyVaultClientIntegrationTestBase.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
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;
	}
 
Example #28
Source File: EcKeyIntegrationTests.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
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;
    }