com.microsoft.aad.adal4j.AuthenticationResult Java Examples

The following examples show how to use com.microsoft.aad.adal4j.AuthenticationResult. 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: AzureComputeServiceImpl.java    From crate with Apache License 2.0 6 votes vote down vote up
private Configuration createConfiguration() {
    Configuration conf = null;
    try {
        AuthenticationResult authRes = AuthHelper.getAccessTokenFromServicePrincipalCredentials(
            Azure.ENDPOINT,
            Azure.AUTH_ENDPOINT,
            tenantId,
            appId,
            appSecret
        );

        DefaultBuilder registry = DefaultBuilder.create();
        AzureConfiguration.registerServices(registry);
        conf = ManagementConfiguration.configure(null, new Configuration(registry),
            URI.create(Azure.ENDPOINT), subscriptionId, authRes.getAccessToken());
    } catch (Exception e) {
        LOGGER.error("Could not create configuration for Azure clients", e);
    }
    return conf;
}
 
Example #2
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Creates a new KeyVaultCredential based on the access token obtained.
 *
 * @return
 */
private ServiceClientCredentials createCredentials() {
    return new KeyVaultCredentials() {

        //Callback that supplies the token type and access token on request.
        @Override
        public String doAuthenticate(String authorization, String resource, String scope) {

            AuthenticationResult authResult;
            try {
                authResult = getAccessToken(authorization, resource);
                return authResult.getAccessToken();
            } catch (Exception e) {
                log.error("Failed to get authentication token for key vault.",e);
                // e.printStackTrace();
            }
            return "";
        }

    };
}
 
Example #3
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Creates a new KeyVaultCredential based on the access token obtained.
 *
 * @return
 */
private ServiceClientCredentials createCredentials() {
    return new KeyVaultCredentials() {

        //Callback that supplies the token type and access token on request.
        @Override
        public String doAuthenticate(String authorization, String resource, String scope) {

            AuthenticationResult authResult;
            try {
                authResult = getAccessToken(authorization, resource);
                return authResult.getAccessToken();
            } catch (Exception e) {
                log.error("Failed to get authentication token for key vault.",e);
                // e.printStackTrace();
            }
            return "";
        }

    };
}
 
Example #4
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 #5
Source File: EcKeyIntegrationTests.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static ServiceClientCredentials createTestCredentials() throws Exception {
    return new KeyVaultCredentials() {

        @Override
        public String doAuthenticate(String authorization, String resource, String scope) {
            try {
                if (isRecordMode()) {
                    AuthenticationResult authResult = getAccessToken(authorization, resource);
                    return authResult.getAccessToken();
                } else {
                    return "";
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
}
 
Example #6
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Creates a new KeyVaultCredential based on the access token obtained.
 *
 * @return
 */
private ServiceClientCredentials createCredentials() {
    return new KeyVaultCredentials() {

        //Callback that supplies the token type and access token on request.
        @Override
        public String doAuthenticate(String authorization, String resource, String scope) {

            AuthenticationResult authResult;
            try {
                authResult = getAccessToken(authorization, resource);
                return authResult.getAccessToken();
            } catch (Exception e) {
                log.error("Failed to get authentication token for key vault.",e);
                // e.printStackTrace();
            }
            return "";
        }

    };
}
 
Example #7
Source File: KeyVaultClientIntegrationTestBase.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static ServiceClientCredentials createTestCredentials() throws Exception {
	return new KeyVaultCredentials() {

		@Override
		public String doAuthenticate(String authorization, String resource, String scope) {
			try {

				if (isRecordMode()) {
					AuthenticationResult authResult = getAccessToken(authorization, resource);
					return authResult.getAccessToken();
				} else {
					return "";
				}

			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
		}
	};
}
 
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: ITManagedStorageAccountKey.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static ServiceClientCredentials createTestCredentials() throws Exception {
    return new KeyVaultCredentials() {

        @Override
        public String doAuthenticate(String authorization, String resource, String scope) {
            try {

                if (isRecordMode()) {
                    AuthenticationResult authResult = getAccessToken(authorization, resource);
                    return authResult.getAccessToken();
                } else {
                    return "";
                }

            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
}
 
Example #10
Source File: KeyVaultClientIntegrationTestBase.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
private static ServiceClientCredentials createTestCredentials() throws Exception {
	return new KeyVaultCredentials() {

		@Override
		public String doAuthenticate(String authorization, String resource, String scope) {
			try {

				if (isRecordMode()) {
					AuthenticationResult authResult = getAccessToken(authorization, resource);
					return authResult.getAccessToken();
				} else {
					return "";
				}

			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
		}
	};
}
 
Example #11
Source File: AzureKms.java    From sfs with Apache License 2.0 6 votes vote down vote up
private CloudCredentials createCredentials(VertxContext<Server> vertxContext) throws Exception {
    return new KeyVaultCredentials() {

        @Override
        public Header doAuthenticate(ServiceRequestContext request, Map<String, String> challenge) {
            try {
                String authorization = challenge.get("authorization");
                String resource = challenge.get("resource");
                AuthenticationResult authResult = getAccessToken(vertxContext, accessKeyId, secretKey, authorization, resource);
                return new BasicHeader("Authorization", authResult.getAccessTokenType() + " " + authResult.getAccessToken());
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
}
 
Example #12
Source File: UserTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
@Override
public synchronized String getToken(String resource) throws IOException {
    // Find exact match for the resource
    AuthenticationResult authenticationResult = tokens.get(resource);
    // Return if found and not expired
    if (authenticationResult != null && authenticationResult.getExpiresOnDate().after(new Date())) {
        return authenticationResult.getAccessToken();
    }
    // If found then refresh
    boolean shouldRefresh = authenticationResult != null;
    // If not found for the resource, but is MRRT then also refresh
    if (authenticationResult == null && !tokens.isEmpty()) {
        authenticationResult = new ArrayList<>(tokens.values()).get(0);
        shouldRefresh = authenticationResult.isMultipleResourceRefreshToken();
    }
    // Refresh
    if (shouldRefresh) {
        authenticationResult = acquireAccessTokenFromRefreshToken(resource, authenticationResult.getRefreshToken());
    }
    // If refresh fails or not refreshable, acquire new token
    if (authenticationResult == null) {
        authenticationResult = acquireNewAccessToken(resource);
    }
    tokens.put(resource, authenticationResult);
    return authenticationResult.getAccessToken();
}
 
Example #13
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 #14
Source File: DelegatedTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
@Override
public synchronized String getToken(String resource) throws IOException {
    // Find exact match for the resource
    AuthenticationResult authenticationResult = tokens.get(resource);
    // Return if found and not expired
    if (authenticationResult != null && authenticationResult.getExpiresOnDate().after(new Date())) {
        return authenticationResult.getAccessToken();
    }
    // If found then refresh
    boolean shouldRefresh = authenticationResult != null;
    // If not found for the resource, but is MRRT then also refresh
    if (authenticationResult == null && !tokens.isEmpty()) {
        authenticationResult = new ArrayList<>(tokens.values()).get(0);
        shouldRefresh = authenticationResult.isMultipleResourceRefreshToken();
    }
    // Refresh
    if (shouldRefresh) {
        authenticationResult = acquireAccessTokenFromRefreshToken(resource, authenticationResult.getRefreshToken());
    }
    // If refresh fails or not refreshable, acquire new token
    if (authenticationResult == null) {
        authenticationResult = acquireNewAccessToken(resource);
    }
    tokens.put(resource, authenticationResult);
    return authenticationResult.getAccessToken();
}
 
Example #15
Source File: KeyVault.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Creates a new KeyVaultCredential based on the access token obtained.
 *
 * @return
 */
private ServiceClientCredentials createCredentials() {
    return new KeyVaultCredentials() {

        //Callback that supplies the token type and access token on request.
        @Override
        public String doAuthenticate(String authorization, String resource, String scope) {

            AuthenticationResult authResult;
            try {
                authResult = getAccessToken(authorization, resource);
                return authResult.getAccessToken();
            } catch (Exception e) {
                // TODO: Add logging
                log.error("Failed to get the saccess token for accessing the keyvault.", e);
                // e.printStackTrace();
            }
            return "";
        }

    };
}
 
Example #16
Source File: AadController.java    From journaldev with MIT License 6 votes vote down vote up
/**
 * getScurePage: Will check for JWT token details and returns aad.jsp view
 * @param model
 * @param httpRequest
 * @return
 */
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String getScurePage(ModelMap model, HttpServletRequest httpRequest) {
	HttpSession session = httpRequest.getSession();
	log.debug("session: " + session);
	AuthenticationResult result = (AuthenticationResult) session.getAttribute(CommonUtil.PRINCIPAL_SESSION_NAME);
	if (result == null) {
		model.addAttribute("error", new Exception("AuthenticationResult not found in session."));
		return "/error";
	} else {
		try {
			log.debug("JWT token details:-");
			JWT jwt = JWTParser.parse(result.getIdToken());
			for (String key : jwt.getJWTClaimsSet().getAllClaims().keySet()) {
				log.info(key + ":" + jwt.getJWTClaimsSet().getAllClaims().get(key));
			}
			model.addAttribute("user", jwt.getJWTClaimsSet().getStringClaim("unique_name"));
		} catch (ParseException e) {
			log.error("Exception:", e);
		}

	}
	return "/secure/aad";
}
 
Example #17
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 #18
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 #19
Source File: AzureClientCredentials.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public Optional<String> getRefreshToken() {
    String refreshToken = null;
    Optional<Boolean> codeGrantFlow = Optional.ofNullable(credentialView.codeGrantFlow());
    if (codeGrantFlow.orElse(Boolean.FALSE)) {
        CbDelegatedTokenCredentials delegatedCredentials = (CbDelegatedTokenCredentials) azureClientCredentials;
        Optional<AuthenticationResult> authenticationResult = delegatedCredentials.getTokens()
                .values()
                .stream()
                .findFirst();

        if (authenticationResult.isPresent()) {
            refreshToken = authenticationResult.get().getRefreshToken();
        }
    }
    return Optional.ofNullable(refreshToken);
}
 
Example #20
Source File: CbDelegatedTokenCredentialsTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #21
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 #22
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 #23
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 #24
Source File: CbDelegatedTokenCredentials.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized String getToken(String resource) throws IOException {
    // Find exact match for the resource
    AuthenticationResult authenticationResult = tokens.get(resource);
    // Return if found and not expired
    if (authenticationResult != null && authenticationResult.getExpiresOnDate().after(new Date())) {
        return authenticationResult.getAccessToken();
    }
    // If found then refresh
    boolean shouldRefresh = authenticationResult != null;
    // If not found for the resource, but is MRRT then also refresh
    if (authenticationResult == null && !tokens.isEmpty()) {
        authenticationResult = new ArrayList<>(tokens.values()).get(0);
        shouldRefresh = authenticationResult.isMultipleResourceRefreshToken();
    }
    // Refresh
    if (shouldRefresh) {
        boolean multipleResourceRefreshToken = authenticationResult.isMultipleResourceRefreshToken();
        String refreshToken = authenticationResult.getRefreshToken();
        authenticationResult = acquireAccessTokenFromRefreshToken(resource, refreshToken, multipleResourceRefreshToken);
    }
    // If refresh fails or not refreshable, acquire new token
    if (authenticationResult == null) {
        authenticationResult = acquireNewAccessToken(resource);
    }
    tokens.put(resource, authenticationResult);
    return authenticationResult.getAccessToken();
}
 
Example #25
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 #26
Source File: MockUserTokenCredentials.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
private void acquireAccessTokenFromRefreshToken() throws IOException {
    this.authenticationResult = new AuthenticationResult(
            null,
            "token2",
            "refresh",
            1,
            null,
            null,
            false);
}
 
Example #27
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 #28
Source File: CbDelegatedTokenCredentials.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private AuthenticationResult acquireAccessTokenFromRefreshToken(String resource, String refreshToken, boolean multipleResourceRefreshToken) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        return cbRefreshTokenClient.refreshToken(domain(), clientId(), clientSecret, resource, refreshToken,
                multipleResourceRefreshToken);
    } catch (Exception e) {
        throw new AuthenticationException("Could not obtain refresh token.", e);
    } finally {
        executor.shutdown();
    }
}
 
Example #29
Source File: AzureClientCredentials.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private AzureTokenCredentials getAzureCredentials() {
    String tenantId = credentialView.getTenantId();
    String clientId = credentialView.getAccessKey();
    String secretKey = credentialView.getSecretKey();
    String subscriptionId = credentialView.getSubscriptionId();
    AzureEnvironment azureEnvironment = AzureEnvironment.AZURE;
    ApplicationTokenCredentials applicationTokenCredentials = new ApplicationTokenCredentials(clientId, tenantId, secretKey, azureEnvironment);
    Optional<Boolean> codeGrantFlow = Optional.ofNullable(credentialView.codeGrantFlow());

    AzureTokenCredentials result = applicationTokenCredentials;
    if (codeGrantFlow.orElse(Boolean.FALSE)) {
        String refreshToken = credentialView.getRefreshToken();
        if (StringUtils.isNotEmpty(refreshToken)) {
            LOGGER.info("Creating Azure credentials for a new delegated token with refresh token, credential: {}", credentialView.getName());
            String resource = azureEnvironment.managementEndpoint();
            CBRefreshTokenClient refreshTokenClient = cbRefreshTokenClientProvider.getCBRefreshTokenClient(azureEnvironment.activeDirectoryEndpoint());
            AuthenticationResult authenticationResult = refreshTokenClient.refreshToken(tenantId, clientId, secretKey, resource, refreshToken, false);

            if (authenticationResult == null) {
                String msg = String.format("New token couldn't be obtain with refresh token for credential: %s", credentialView.getName());
                LOGGER.warn(msg);
                throw new CloudConnectorException(msg);
            }

            Map<String, AuthenticationResult> tokens = Map.of(resource, authenticationResult);
            result = new CbDelegatedTokenCredentials(applicationTokenCredentials, resource, tokens, secretKey, authenticationContextProvider,
                    cbRefreshTokenClientProvider);
        } else {
            LOGGER.info("Creating Azure credentials for a new delegated token with authorization code, credential: {}", credentialView.getName());
            String appReplyUrl = credentialView.getAppReplyUrl();
            String authorizationCode = credentialView.getAuthorizationCode();
            result = new CbDelegatedTokenCredentials(applicationTokenCredentials, appReplyUrl, authorizationCode, secretKey, authenticationContextProvider,
                    cbRefreshTokenClientProvider);
        }
    } else {
        LOGGER.info("Creating Azure credentials with application token credentials, credential: {}", credentialView.getName());
    }
    return result.withDefaultSubscriptionId(subscriptionId);
}
 
Example #30
Source File: CbDelegatedTokenCredentials.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public CbDelegatedTokenCredentials(ApplicationTokenCredentials applicationCredentials, String redirectUrl, Map<String, AuthenticationResult> tokens,
        String clientSecret, AuthenticationContextProvider authenticationContextProvider, CBRefreshTokenClientProvider cbRefreshTokenClientProvider) {
    super(applicationCredentials.environment(), applicationCredentials.domain());
    this.authenticationContextProvider = authenticationContextProvider;
    this.tokens = new ConcurrentHashMap<>(tokens);
    this.redirectUrl = redirectUrl;
    cbRefreshTokenClient = cbRefreshTokenClientProvider.getCBRefreshTokenClient(applicationCredentials.environment().activeDirectoryEndpoint());
    this.clientSecret = clientSecret;
    this.applicationCredentials = applicationCredentials;
}