com.microsoft.aad.adal4j.UserInfo Java Examples

The following examples show how to use com.microsoft.aad.adal4j.UserInfo. 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: 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 #2
Source File: AadAuthenticationHelperTest.java    From azure-kusto-java with MIT License 5 votes vote down vote up
@Test
@DisplayName("validate cached token. Refresh if needed. Call regularly if no refresh token")
void useCachedTokenAndRefreshWhenNeeded() throws InterruptedException, ExecutionException, ServiceUnavailableException, IOException, DataServiceException, URISyntaxException, CertificateException, OperatorCreationException, PKCSException {
    String certFilePath = Paths.get("src", "test", "resources", "cert.cer").toString();
    String privateKeyPath = Paths.get("src", "test", "resources", "key.pem").toString();

    X509Certificate x509Certificate = readPem(certFilePath, "basic").getCertificate();
    PrivateKey privateKey = readPem(privateKeyPath, "basic").getKey();

    ConnectionStringBuilder csb = ConnectionStringBuilder
            .createWithAadApplicationCertificate("resource.uri", "client-id", x509Certificate, privateKey);

    AadAuthenticationHelper aadAuthenticationHelperSpy = spy(new AadAuthenticationHelper(csb));

    AuthenticationResult authenticationResult = new AuthenticationResult("testType", "firstToken", "refreshToken", 0, "id", mock(UserInfo.class), false);
    AuthenticationResult authenticationResultFromRefresh = new AuthenticationResult("testType", "fromRefresh", null, 90, "id", mock(UserInfo.class), false);
    AuthenticationResult authenticationResultNullRefreshTokenResult = new AuthenticationResult("testType", "nullRefreshResult", null, 0, "id", mock(UserInfo.class), false);

    doReturn(authenticationResultFromRefresh).when(aadAuthenticationHelperSpy).acquireAccessTokenByRefreshToken();
    doReturn(authenticationResult).when(aadAuthenticationHelperSpy).acquireWithClientCertificate();

    assertEquals("firstToken", aadAuthenticationHelperSpy.acquireAccessToken());

    // Token was passed as expired - expected to be refreshed
    assertEquals("fromRefresh", aadAuthenticationHelperSpy.acquireAccessToken());

    // Token is still valid - expected to return the same
    assertEquals("fromRefresh", aadAuthenticationHelperSpy.acquireAccessToken());

    doReturn(new Date(System.currentTimeMillis() + MIN_ACCESS_TOKEN_VALIDITY_IN_MILLISECS * 2)).when(aadAuthenticationHelperSpy).dateInAMinute();
    doReturn(authenticationResultNullRefreshTokenResult).when(aadAuthenticationHelperSpy).acquireWithClientCertificate();

    // Null refresh token + token is now expired- expected to authenticate again and reacquire token
    assertEquals("nullRefreshResult", aadAuthenticationHelperSpy.acquireAccessToken());
}
 
Example #3
Source File: CbDelegatedTokenCredentialsTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #4
Source File: CbDelegatedTokenCredentialsTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #5
Source File: CbDelegatedTokenCredentialsTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #6
Source File: AzureClientCredentialsTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    when(credentialView.codeGrantFlow()).thenReturn(true);
    when(credentialView.getTenantId()).thenReturn(TENANT_ID);
    when(credentialView.getAccessKey()).thenReturn(ACCESS_KEY);
    when(credentialView.getSecretKey()).thenReturn(SECRET_KEY);
    when(credentialView.getName()).thenReturn(CREDENTIAL_NAME);
    when(credentialView.getSubscriptionId()).thenReturn(SUBSCRIPTION_ID);
    when(cbRefreshTokenClientProvider.getCBRefreshTokenClient(eq(AzureEnvironment.AZURE.activeDirectoryEndpoint()))).thenReturn(cbRefreshTokenClient);
    authenticationResult = new AuthenticationResult("type", ACCESS_TOKEN, REFRESH_TOKEN, 123456789L, "1", mock(UserInfo.class), true);
}
 
Example #7
Source File: AzureAdCredential.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getPermissions() {
    if (permissions == null) {
        final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
        final Set<String> permissionSet = new HashSet<>();
        final UserInfo userInfo = authResult.getUserInfo();
        permissionSet.add(systemHelper.getSearchRoleByUser(userInfo.getUniqueId()));
        permissionSet.add(systemHelper.getSearchRoleByUser(userInfo.getDisplayableId()));
        stream(groups).of(stream -> stream.forEach(s -> permissionSet.add(systemHelper.getSearchRoleByGroup(s))));
        stream(roles).of(stream -> stream.forEach(s -> permissionSet.add(systemHelper.getSearchRoleByRole(s))));
        permissions = permissionSet.stream().filter(StringUtil::isNotBlank).distinct().toArray(n -> new String[n]);
    }
    return permissions;
}