Search in sources :

Example 1 with JsFunctionRegistry

use of org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry in project carbon-identity-framework by wso2.

the class JsGraphBuilder method createWith.

/**
 * Creates the graph with the given Script and step map.
 *
 * @param script the Dynamic authentication script.
 */
public JsGraphBuilder createWith(String script) {
    try {
        currentBuilder.set(this);
        Bindings globalBindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_EXECUTE_STEP, (StepExecutor) this::executeStep);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SEND_ERROR, (BiConsumer<String, Map>) this::sendError);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_AUTH_FAILURE, (FailAuthenticationFunction) this::fail);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SHOW_PROMPT, (PromptExecutor) this::addShowPrompt);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_LOAD_FUNC_LIB, (LoadExecutor) this::loadLocalLibrary);
        JsFunctionRegistry jsFunctionRegistrar = FrameworkServiceDataHolder.getInstance().getJsFunctionRegistry();
        if (jsFunctionRegistrar != null) {
            Map<String, Object> functionMap = jsFunctionRegistrar.getSubsystemFunctionsMap(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER);
            functionMap.forEach(globalBindings::put);
        }
        Invocable invocable = (Invocable) engine;
        engine.eval(FrameworkServiceDataHolder.getInstance().getCodeForRequireFunction());
        removeDefaultFunctions(engine);
        String identifier = UUID.randomUUID().toString();
        JSExecutionMonitorData scriptExecutionData;
        try {
            startScriptExecutionMonitor(identifier, authenticationContext);
            engine.eval(script);
            invocable.invokeFunction(FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST, new JsAuthenticationContext(authenticationContext));
        } finally {
            scriptExecutionData = endScriptExecutionMonitor(identifier);
        }
        storeAuthScriptExecutionMonitorData(authenticationContext, scriptExecutionData);
        JsGraphBuilderFactory.persistCurrentContext(authenticationContext, engine);
    } catch (ScriptException e) {
        result.setBuildSuccessful(false);
        result.setErrorReason("Error in executing the Javascript. Nested exception is: " + e.getMessage());
        if (log.isDebugEnabled()) {
            log.debug("Error in executing the Javascript.", e);
        }
    } catch (NoSuchMethodException e) {
        result.setBuildSuccessful(false);
        result.setErrorReason("Error in executing the Javascript. " + FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST + " function is not defined.");
        if (log.isDebugEnabled()) {
            log.debug("Error in executing the Javascript.", e);
        }
    } finally {
        clearCurrentBuilder();
    }
    return this;
}
Also used : JsFunctionRegistry(org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry) Bindings(javax.script.Bindings) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) JsAuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext) JSObject(jdk.nashorn.api.scripting.JSObject) BiConsumer(java.util.function.BiConsumer)

Example 2 with JsFunctionRegistry

use of org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry in project carbon-identity-framework by wso2.

the class GraphBasedSequenceHandlerAbstractTest method setupSuite.

@BeforeClass
protected void setupSuite() {
    configurationLoader = new UIBasedConfigurationLoader();
    graphBuilderFactory = new JsGraphBuilderFactory();
    JsFunctionRegistryImpl jsFunctionRegistry = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistry);
    graphBuilderFactory.init();
    FrameworkServiceDataHolder.getInstance().setJsGraphBuilderFactory(graphBuilderFactory);
    AsyncSequenceExecutor asyncSequenceExecutor = new AsyncSequenceExecutor();
    asyncSequenceExecutor.init();
    FrameworkServiceDataHolder.getInstance().setAsyncSequenceExecutor(asyncSequenceExecutor);
}
Also used : UIBasedConfigurationLoader(org.wso2.carbon.identity.application.authentication.framework.config.loader.UIBasedConfigurationLoader) JsGraphBuilderFactory(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilderFactory) JsFunctionRegistryImpl(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsFunctionRegistryImpl) BeforeClass(org.testng.annotations.BeforeClass)

Example 3 with JsFunctionRegistry

use of org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry in project carbon-identity-framework by wso2.

the class GraphBasedSequenceHandlerCustomFunctionsTest method testHandleDynamicBoolean.

public void testHandleDynamicBoolean() throws Exception {
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
    JsFunctionRegistry jsFunctionRegistrar = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistrar);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "fn1", (Function<JsAuthenticationContext, String>) GraphBasedSequenceHandlerCustomFunctionsTest::customFunction1);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getTrueFunction", (Function<JsAuthenticationContext, Boolean>) GraphBasedSequenceHandlerCustomFunctionsTest::customBoolean);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getTrueFunction2", (BiFunction<JsAuthenticationContext, String, Boolean>) GraphBasedSequenceHandlerCustomFunctionsTest::customBoolean2);
    ServiceProvider sp1 = getTestServiceProvider("js-sp-dynamic-1.xml");
    String script = "var onLoginRequest = function(context) {\n" + "    var myBool = getTrueFunction2(context, 'a');\n" + "    Log.info(\"My Bool Value \"+myBool);\n" + "    if(myBool) {\n" + "        Log.info(\"My Bool Is Selected \"+myBool);\n" + "        executeStep(1, {\n" + "            onSuccess : function(context) {\n" + "                executeStep(3);\n" + "            }\n" + "        });\n" + "        executeStep(2);\n" + "    }  else {\n" + "        Log.info(\"My Bool Not Selected \"+myBool);\n" + "        executeStep(1);\n" + "        executeStep(3);\n" + "    }\n" + "};";
    sp1.getLocalAndOutBoundAuthenticationConfig().getAuthenticationScriptConfig().setContent(script);
    AuthenticationContext context = processAndGetAuthenticationContext(new String[0], sp1);
    List<AuthHistory> authHistories = context.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(authHistories.size(), 3);
    assertEquals(authHistories.get(0).getAuthenticatorName(), "BasicMockAuthenticator");
    assertEquals(authHistories.get(1).getAuthenticatorName(), "FptMockAuthenticator");
    assertEquals(authHistories.get(2).getAuthenticatorName(), "HwkMockAuthenticator");
}
Also used : 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) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)

Example 4 with JsFunctionRegistry

use of org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry 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 5 with JsFunctionRegistry

use of org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry in project carbon-identity-framework by wso2.

the class ConditionalAuthenticationMgtService method getAllAvailableFunctions.

/**
 * Gets the list of available functions for the conditional authentication script. This includes the core
 * functions and the custom functions that will be registered via OSGi.
 *
 * @return list of all the functions.
 */
public String[] getAllAvailableFunctions() {
    List<String> jsFunctions = Stream.of("executeStep", "selectAcrFrom", "sendError", "Log.info", "require").collect(Collectors.toList());
    JsFunctionRegistry jsFunctionRegistry = FrameworkServiceDataHolder.getInstance().getJsFunctionRegistry();
    Map<String, Object> functionsMap = jsFunctionRegistry.getSubsystemFunctionsMap(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER);
    if (functionsMap != null) {
        jsFunctions.addAll(functionsMap.keySet());
    }
    return jsFunctions.toArray(new String[0]);
}
Also used : JsFunctionRegistry(org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry)

Aggregations

JsFunctionRegistry (org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry)5 JsFunctionRegistryImpl (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsFunctionRegistryImpl)4 JsAuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext)3 AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)2 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)2 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)2 BiConsumer (java.util.function.BiConsumer)1 Bindings (javax.script.Bindings)1 Invocable (javax.script.Invocable)1 ScriptException (javax.script.ScriptException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 JSObject (jdk.nashorn.api.scripting.JSObject)1 BeforeClass (org.testng.annotations.BeforeClass)1 DataProvider (org.testng.annotations.DataProvider)1 Test (org.testng.annotations.Test)1 UIBasedConfigurationLoader (org.wso2.carbon.identity.application.authentication.framework.config.loader.UIBasedConfigurationLoader)1 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)1 JsGraphBuilderFactory (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilderFactory)1