Search in sources :

Example 6 with JsAuthenticationContext

use of org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext in project carbon-identity-framework by wso2.

the class GraphBasedSequenceHandlerCustomFunctionsTest method testHandleDynamicJavascriptSerialization.

@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");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JsFunctionRegistry(org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry) JsAuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext) AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) JsAuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext) JsFunctionRegistryImpl(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsFunctionRegistryImpl) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) HttpServletResponse(javax.servlet.http.HttpServletResponse) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) Test(org.testng.annotations.Test)

Example 7 with JsAuthenticationContext

use of org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext in project identity-conditional-auth-functions by wso2-extensions.

the class PublishToAnalyticsFunctionImpl method publishToAnalytics.

@Override
public void publishToAnalytics(Map<String, String> metadata, Map<String, Object> payloadData, JsAuthenticationContext context) {
    String appName = metadata.get(PARAM_APP_NAME);
    String inputStream = metadata.get(PARAM_INPUT_STREAM);
    String targetPath = metadata.get(PARAM_EP_URL);
    String epUrl = null;
    try {
        if (appName != null && inputStream != null) {
            epUrl = "/" + appName + "/" + inputStream;
        } else if (targetPath != null) {
            epUrl = targetPath;
        } else {
            LOG.error("Target path cannot be found.");
            return;
        }
        String tenantDomain = context.getContext().getTenantDomain();
        String targetHostUrl = CommonUtils.getConnectorConfig(AnalyticsEngineConfigImpl.RECEIVER, tenantDomain);
        if (targetHostUrl == null) {
            LOG.error("Target host cannot be found.");
            return;
        }
        HttpPost request = new HttpPost(epUrl);
        request.setHeader(CONTENT_TYPE, TYPE_APPLICATION_JSON);
        handleAuthentication(request, tenantDomain);
        JSONObject jsonObject = new JSONObject();
        JSONObject event = new JSONObject();
        for (Map.Entry<String, Object> dataElements : payloadData.entrySet()) {
            event.put(dataElements.getKey(), dataElements.getValue());
        }
        jsonObject.put("event", event);
        request.setEntity(new StringEntity(jsonObject.toJSONString()));
        String[] targetHostUrls = targetHostUrl.split(";");
        HttpHost[] targetHosts = new HttpHost[targetHostUrls.length];
        for (int i = 0; i < targetHostUrls.length; i++) {
            URL hostUrl = new URL(targetHostUrls[i]);
            targetHosts[i] = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), hostUrl.getProtocol());
        }
        CloseableHttpAsyncClient client = ClientManager.getInstance().getClient(tenantDomain);
        for (final HttpHost targetHost : targetHosts) {
            client.execute(targetHost, request, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    int responseCode = response.getStatusLine().getStatusCode();
                    if (responseCode == 200) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Successfully published data to the analytics for session data key: " + context.getContext().getContextIdentifier());
                        }
                    } else {
                        LOG.error("Error while publishing data to analytics engine for session data key: " + context.getContext().getContextIdentifier() + ". Request completed successfully. " + "But response code was not 200");
                    }
                }

                @Override
                public void failed(final Exception ex) {
                    LOG.error("Error while publishing data to analytics engine for session data key: " + context.getContext().getContextIdentifier() + ". Request failed with: " + ex);
                }

                @Override
                public void cancelled() {
                    LOG.error("Error while publishing data to analytics engine for session data key: " + context.getContext().getContextIdentifier() + ". Request canceled.");
                }
            });
        }
    } catch (IOException e) {
        LOG.error("Error while calling analytics engine for tenant: " + context.getContext().getTenantDomain(), e);
    } catch (IdentityEventException e) {
        LOG.error("Error while preparing authentication information for tenant: " + context.getContext().getTenantDomain(), e);
    } catch (FrameworkException e) {
        LOG.error("Error while building client to invoke analytics engine for tenant: " + context.getContext().getTenantDomain(), e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL) IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) IOException(java.io.IOException) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) HttpHost(org.apache.http.HttpHost) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) JSONObject(org.json.simple.JSONObject) Map(java.util.Map)

Example 8 with JsAuthenticationContext

use of org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext in project identity-conditional-auth-functions by wso2-extensions.

the class UserStoreFunctions method getUniqueUserWithClaimValues.

public JsAuthenticatedUser getUniqueUserWithClaimValues(Map<String, String> claimMap, Object... parameters) throws FrameworkException {
    JsAuthenticationContext authenticationContext = null;
    String tenantDomain = null;
    String profile = "default";
    if (claimMap == null || parameters == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Passed parameter to getUniqueUserWithClaimValues method has null values");
        }
        return null;
    }
    if (parameters.length == 2) {
        if (parameters[0] instanceof JsAuthenticationContext) {
            authenticationContext = (JsAuthenticationContext) parameters[0];
            tenantDomain = authenticationContext.getContext().getTenantDomain();
        }
        if (parameters[1] instanceof String) {
            profile = (String) parameters[1];
        }
    }
    if (parameters.length == 1 && parameters[0] instanceof JsAuthenticationContext) {
        authenticationContext = (JsAuthenticationContext) parameters[0];
        tenantDomain = authenticationContext.getContext().getTenantDomain();
    }
    if (tenantDomain != null) {
        int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        try {
            List<String> selectedUsers = new ArrayList<>();
            UserRealm userRealm = UserStoreFunctionsServiceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
            if (userRealm != null) {
                UserStoreManager userStoreManager = (UserStoreManager) userRealm.getUserStoreManager();
                // Get the user list using the first Claim value
                Map.Entry<String, String> claimEntry = claimMap.entrySet().iterator().next();
                String firstClaim = claimEntry.getKey();
                String firstClaimValue = claimEntry.getValue();
                claimMap.remove(firstClaim);
                String[] userList = userStoreManager.getUserList(firstClaim, firstClaimValue, profile);
                if (userList == null) {
                    return null;
                }
                selectedUsers.addAll(Arrays.asList(userList));
                for (String userName : userList) {
                    for (Map.Entry<String, String> entry : claimMap.entrySet()) {
                        String userClaimValue = userStoreManager.getUserClaimValue(userName, entry.getKey(), profile);
                        if (userClaimValue == null || !userClaimValue.equals(entry.getValue())) {
                            selectedUsers.remove(userName);
                            break;
                        }
                    }
                }
                if (selectedUsers.isEmpty()) {
                    return null;
                }
                if (selectedUsers.size() > 1) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("There are more than one user with the provided claim values.");
                    }
                    return null;
                }
                String username = selectedUsers.get(0);
                AuthenticatedUser authenticatedUser = new AuthenticatedUser();
                if (username.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) {
                    String[] subjectIdentifierSplits = username.split(CarbonConstants.DOMAIN_SEPARATOR, 2);
                    authenticatedUser.setUserStoreDomain(subjectIdentifierSplits[0]);
                    username = subjectIdentifierSplits[1];
                } else {
                    authenticatedUser.setUserStoreDomain(IdentityUtil.getPrimaryDomainName());
                }
                authenticatedUser.setUserName(username);
                authenticatedUser.setTenantDomain(tenantDomain);
                if (authenticationContext != null) {
                    return new JsAuthenticatedUser(authenticationContext.getContext(), authenticatedUser);
                }
                return new JsAuthenticatedUser(authenticatedUser);
            } else {
                LOG.error("Cannot find the user realm for the given tenant: " + tenantId);
            }
        } catch (UserStoreException e) {
            String msg = "getUserListWithClaimValue Function failed while getting user attributes ";
            if (LOG.isDebugEnabled()) {
                LOG.debug(msg, e);
            }
            throw new FrameworkException(msg, e);
        }
    }
    return null;
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) ArrayList(java.util.ArrayList) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) JsAuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticatedUser) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) JsAuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticatedUser) JsAuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext) UserRealm(org.wso2.carbon.user.api.UserRealm) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Map(java.util.Map)

Example 9 with JsAuthenticationContext

use of org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext in project identity-conditional-auth-functions by wso2-extensions.

the class GetSessionDataFunction method getData.

/**
 * This function will contain the implementation for retrieving data.
 *
 * @param context AuthenticationContext object passed from Javascript
 * @param map     parameter map
 * @return Map of sessionID and sessions
 * @throws FrameworkException
 */
@Override
public Map<String, Session> getData(JsAuthenticationContext context, Map<String, String> map) throws FrameworkException {
    Map<String, Session> sessionMap = new HashMap<>();
    AuthenticatedUser authenticatedUser = context.getWrapped().getLastAuthenticatedUser();
    if (authenticatedUser == null) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to find the authenticated user from the Authentication context.");
        }
        throw new FrameworkException("Authentication user not found");
    }
    try {
        List<Session> sessionList = SessionValidationUtil.getSessionDetails(authenticatedUser);
        for (Session session : sessionList) {
            sessionMap.put(session.getSessionId(), session);
        }
    } catch (IOException | SessionValidationException e) {
        log.error("Failed to retrieve active session details", e);
    }
    return sessionMap;
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) HashMap(java.util.HashMap) IOException(java.io.IOException) SessionValidationException(org.wso2.carbon.identity.conditional.auth.functions.session.exception.SessionValidationException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) Session(org.wso2.carbon.identity.conditional.auth.functions.session.model.Session)

Example 10 with JsAuthenticationContext

use of org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext in project identity-conditional-auth-functions by wso2-extensions.

the class IsWithinSessionLimitFunctionImpl method validate.

/**
 * Method to validate user session a given the authentication context and set of required attributes.
 *
 * @param context Authentication context
 * @param map     Hash map of attributes required for validation
 * @return boolean value indicating the validation success/failure
 * @throws FrameworkException when exception occurred in session retrieving method
 */
@Override
public boolean validate(JsAuthenticationContext context, Map<String, String> map) throws FrameworkException {
    boolean state = false;
    int sessionLimit = getSessionLimitFromMap(map);
    AuthenticatedUser authenticatedUser = context.getWrapped().getLastAuthenticatedUser();
    if (authenticatedUser == null) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to find the authenticated user from the Authentication context.");
        }
        throw new FrameworkException("Unable to find the Authenticated user from previous step");
    }
    int sessionCount = getActiveSessionCount(authenticatedUser);
    if (log.isDebugEnabled()) {
        log.debug("Active session count: " + sessionCount + " and session limit : " + sessionLimit);
    }
    if (sessionCount < sessionLimit) {
        state = true;
    }
    return state;
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

JsAuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext)10 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)10 Test (org.testng.annotations.Test)9 Bindings (javax.script.Bindings)6 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)6 JsFunctionRegistryImpl (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsFunctionRegistryImpl)5 AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)5 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)4 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)4 JsFunctionRegistry (org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry)3 JsGraphBuilder (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder)3 JsGraphBuilderFactory (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilderFactory)3 SerializableJsFunction (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.SerializableJsFunction)3 FrameworkServiceDataHolder (org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder)3 IOException (java.io.IOException)2 Map (java.util.Map)2 EndStep (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.EndStep)2 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)2 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1