Java Code Examples for org.wso2.carbon.user.core.util.UserCoreUtil#setDomainInThreadLocal()

The following examples show how to use org.wso2.carbon.user.core.util.UserCoreUtil#setDomainInThreadLocal() . 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: GraphBasedSequenceHandlerNoJsTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "noJsDataProvider")
public void testHandleStaticSequence(String spFileName, int authHistoryCount) throws
        Exception {
    ServiceProvider sp1 = getTestServiceProvider(spFileName);

    AuthenticationContext context = getAuthenticationContext(sp1);

    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.<String, String[]>emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = mock(HttpServletRequest.class);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);

    List<AuthHistory> authHistories = context.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(authHistories.size(), authHistoryCount);
}
 
Example 2
Source File: GraphBasedSequenceHandlerCustomFunctionsTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private AuthenticationContext processAndGetAuthenticationContext(String[] acrArray, ServiceProvider sp1)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, FrameworkException {
    AuthenticationContext context = getAuthenticationContext(sp1);
    if (acrArray != null) {
        for (String acr : acrArray) {
            context.addRequestedAcr(acr);
        }
    }

    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.<String, String[]>emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = mock(HttpServletRequest.class);
    addMockAttributes(req);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);
    return context;
}
 
Example 3
Source File: PostAuthAssociationHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To set the associated local user in automation context and to add the relevant claims.
 *
 * @param associatedLocalUserName Associated Local username.
 * @param context                 Authentication context.
 * @param stepConfig              Configuration related with current authentication step.
 * @throws PostAuthenticationFailedException Post Authentication failed exception.
 */
private void setAssociatedLocalUserToContext(String associatedLocalUserName, AuthenticationContext context,
        StepConfig stepConfig) throws PostAuthenticationFailedException {

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    String fullQualifiedAssociatedUserId = FrameworkUtils.prependUserStoreDomainToName(
            associatedLocalUserName + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
    UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedLocalUserName));
    sequenceConfig.setAuthenticatedUser(
            AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(fullQualifiedAssociatedUserId));
    sequenceConfig.getApplicationConfig().setMappedSubjectIDSelected(true);

    Map<String, String> mappedAttrs = handleClaimMappings(stepConfig, context);
    handleRoleMapping(context, sequenceConfig, mappedAttrs);
    Map<ClaimMapping, String> authenticatedUserAttributes = getClaimMapping(context, mappedAttrs);
    if (MapUtils.isNotEmpty(authenticatedUserAttributes)) {
        sequenceConfig.getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
        if (log.isDebugEnabled()) {
            log.debug("Local claims from the local user: " + associatedLocalUserName + ", set as "
                    + "user attributed for the federated scenario");
        }
    }
    // in this case associatedID is a local user name - belongs to a tenant in IS.
    String tenantDomain = MultitenantUtils.getTenantDomain(associatedLocalUserName);
    Map<String, Object> authProperties = context.getProperties();

    if (authProperties == null) {
        authProperties = new HashMap<>();
        context.setProperties(authProperties);
    }
    authProperties.put(USER_TENANT_DOMAIN, tenantDomain);
    if (log.isDebugEnabled()) {
        log.debug(
                "Authenticated User: " + sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
        log.debug("Authenticated User Tenant Domain: " + tenantDomain);
    }
}
 
Example 4
Source File: JITProvisioningPostAuthenticationHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To get the authentication context and to call the handle method of the PostJitProvisioningHandler.
 *
 * @param sp1 Service Provider
 * @return relevant authentication context.
 * @throws FrameworkException Framwork Exception.
 */
private AuthenticationContext processAndGetAuthenticationContext(ServiceProvider sp1, boolean
        withAuthenticatedUser, boolean isFederated) throws FrameworkException {

    AuthenticationContext context = getAuthenticationContext(sp1);
    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);
    context.setProperty(FrameworkConstants.STEP_BASED_SEQUENCE_HANDLER_TRIGGERED, true);

    ApplicationAuthenticator applicationAuthenticator = mock(ApplicationAuthenticator.class);

    if (isFederated) {
        applicationAuthenticator = mock(FederatedApplicationAuthenticator.class);
    }
    when(applicationAuthenticator.getName()).thenReturn("Authenticator1");

    if (withAuthenticatedUser) {
        AuthenticatedUser authenticatedUser = new AuthenticatedUser();
        authenticatedUser.setUserName("test");
        authenticatedUser.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        authenticatedUser.setAuthenticatedSubjectIdentifier("test");
        sequenceConfig.setAuthenticatedUser(authenticatedUser);

        AuthenticatorConfig authenticatorConfig = new AuthenticatorConfig();
        authenticatorConfig.setApplicationAuthenticator(applicationAuthenticator);
        for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
            StepConfig stepConfig = entry.getValue();
            stepConfig.setAuthenticatedAutenticator(authenticatorConfig);
            stepConfig.setAuthenticatedUser(authenticatedUser);
        }
        context.setSequenceConfig(sequenceConfig);
    }

    UserCoreUtil.setDomainInThreadLocal("test_domain");
    return context;
}
 
Example 5
Source File: GraphBasedSequenceHandlerAcrTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "staticAcrDataProvider")
public void testHandleStaticJavascriptAcr(String spFileName, String[] acrArray, int authHistoryCount) throws
        Exception {

    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);

    ServiceProvider sp1 = getTestServiceProvider(spFileName);

    AuthenticationContext context = getAuthenticationContext(sp1);
    if (acrArray != null) {
        for (String acr : acrArray) {
            context.addRequestedAcr(acr);
        }
    }

    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.<String, String[]>emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = mock(HttpServletRequest.class);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);

    List<AuthHistory> authHistories = context.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(authHistories.size(), authHistoryCount);
}
 
Example 6
Source File: GraphBasedSequenceHandlerLongWaitTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleLongWait() throws Exception {

    JsFunctionRegistryImpl jsFunctionRegistrar = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistrar);
    LongWaitStatusDAOImpl daoImpl = new LongWaitStatusDAOImpl();
    CacheBackedLongWaitStatusDAO cacheBackedDao = new CacheBackedLongWaitStatusDAO(daoImpl);
    FrameworkServiceDataHolder.getInstance().setLongWaitStatusStoreService(new LongWaitStatusStoreService
            (cacheBackedDao, 5000));
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "testLongWaitCall",
            new AsyncAnalyticsCbFunctionImpl());

    ServiceProvider sp1 = getTestServiceProvider("js-sp-longwait-1.xml");
    AuthenticationContext context = getAuthenticationContext(sp1);
    context.setSessionIdentifier("1234");
    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = createMockHttpServletRequest();

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);

}
 
Example 7
Source File: GraphBasedSequenceHandlerExceptionRetryTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void testExceptionRetry() throws
        Exception {

    JsFunctionRegistryImpl jsFunctionRegistrar = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistrar);
    LongWaitStatusDAOImpl daoImpl = new LongWaitStatusDAOImpl();
    CacheBackedLongWaitStatusDAO cacheBackedDao = new CacheBackedLongWaitStatusDAO(daoImpl);

    FrameworkServiceDataHolder.getInstance().getAuthenticators().add(
            new FailingMockAuthenticator("FailingMockAuthenticator"));

    FrameworkServiceDataHolder.getInstance().setLongWaitStatusStoreService(new LongWaitStatusStoreService
            (cacheBackedDao, 5000));
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "hasAnyOfTheRoles",
            (BiFunction<JsAuthenticatedUser, List<String>, Boolean>) this::hasAnyOfTheRolesFunction);

    ServiceProvider sp1 = getTestServiceProvider("js-sp-exception-retry.xml");
    AuthenticationContext context = getAuthenticationContext(sp1);
    context.setSessionIdentifier("1234");
    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = createMockHttpServletRequest();

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);

    Integer currentAttempts = (Integer) context.getProperties().get(CONTEXT_ATTRIBUTE_NAME_CURRENT_FAIL_TRIES);

    Assert.assertNotNull(currentAttempts);
    Assert.assertEquals(currentAttempts.intValue(), 2);
}
 
Example 8
Source File: GraphBasedSequenceHandlerCustomFunctionsTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleDynamicJavascriptSerialization() throws Exception {

    JsFunctionRegistry jsFunctionRegistrar = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistrar);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "fn1",
            (Function<JsAuthenticationContext, String>) GraphBasedSequenceHandlerCustomFunctionsTest::customFunction1);

    ServiceProvider sp1 = getTestServiceProvider("js-sp-dynamic-1.xml");

    AuthenticationContext context = getAuthenticationContext(sp1);

    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.<String, String[]>emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    byte[] serialized = SerializationUtils.serialize(context);

    AuthenticationContext deseralizedContext = (AuthenticationContext) SerializationUtils.deserialize(serialized);
    assertNotNull(deseralizedContext);

    HttpServletRequest req = mock(HttpServletRequest.class);
    addMockAttributes(req);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, deseralizedContext);

    List<AuthHistory> authHistories = deseralizedContext.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(3, authHistories.size());
    assertEquals(authHistories.get(0).getAuthenticatorName(), "BasicMockAuthenticator");
    assertEquals(authHistories.get(1).getAuthenticatorName(), "HwkMockAuthenticator");
    assertEquals(authHistories.get(2).getAuthenticatorName(), "FptMockAuthenticator");
}
 
Example 9
Source File: GraphBasedSequenceHandlerAcrTest.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = FrameworkException.class)
public void testHandleIncorrectJavascriptAcr() throws Exception {
    ServiceProvider sp1 = getTestServiceProvider("incorrect-js-sp-1.xml");

    AuthenticationContext context = getAuthenticationContext(sp1);

    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.<String, String[]>emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = mock(HttpServletRequest.class);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);

}
 
Example 10
Source File: GraphBasedSequenceHandlerAcrTest.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = FrameworkException.class)
public void testHandleIncorrectFunctionJavascriptAcr() throws Exception {
    ServiceProvider sp1 = getTestServiceProvider("incorrect-function-js-sp-1.xml");

    AuthenticationContext context = getAuthenticationContext(sp1);

    SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    HttpServletRequest req = mock(HttpServletRequest.class);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, context);

}
 
Example 11
Source File: GraphBasedSequenceHandlerClaimMappingsTest.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public void testHandleClaimHandling() throws Exception {

        ServiceProvider sp1 = getTestServiceProvider("js-sp-4-claim.xml");

        AuthenticationContext context = getAuthenticationContext(sp1);

        SequenceConfig sequenceConfig = configurationLoader
            .getSequenceConfig(context, Collections.emptyMap(), sp1);
        context.setSequenceConfig(sequenceConfig);

        HttpServletRequest req = createMockHttpServletRequest();

        HttpServletResponse resp = mock(HttpServletResponse.class);

        UserCoreUtil.setDomainInThreadLocal("test_domain");

        RealmService currentRealmService = FrameworkServiceDataHolder.getInstance().getRealmService();

        RealmService mockRealmService = mock(RealmService.class);
        UserRealm mockUserRealm = mock(UserRealm.class);
        UserStoreManager mockUserStoreManager = mock(UserStoreManager.class);
        when(mockRealmService.getTenantUserRealm(anyInt())).thenReturn(mockUserRealm);
        when(mockUserRealm.getUserStoreManager()).thenReturn(mockUserStoreManager);
        FrameworkServiceDataHolder.getInstance().setRealmService(mockRealmService);
        when(mockUserStoreManager.getUserClaimValues(anyString(), eq(new String[]{"http://wso2.org/claims/givenname"})
            , anyString())).thenReturn(Collections.singletonMap("http://wso2.org/claims/givenname", "Test"));
        when(mockUserStoreManager.getUserClaimValues(anyString(), eq(new String[]{"http://wso2.org/claims/lastname"})
            , anyString())).thenReturn(Collections.singletonMap("http://wso2.org/claims/lastname", "User"));

        final String[] claimValue = {null};

        doAnswer((Answer<Void>) invocationOnMock -> {

            Object[] arguments = invocationOnMock.getArguments();
            claimValue[0] = ((Map<String, String>) arguments[1]).get("http://wso2.org/claims/displayName");
            return null;
        }).when(mockUserStoreManager).setUserClaimValues(anyString(), anyMap(), anyString());

        graphBasedSequenceHandler.handle(req, resp, context);

        FrameworkServiceDataHolder.getInstance().setRealmService(currentRealmService);
        assertEquals(claimValue[0], "Test User by Javascript");
    }