How to introduce new JS API to WSO2 Identity Server Adaptive Authentication Script Configuration
In my previous post [1] I have explained power of WSO2 Identity Server 5.7.0 with Adoptive Authentication support. The idea of this post is to provide step by step guidance to introduce new JS API to JS based authentication configuration. If you have a look at [2] you will see plenty of available JS APIs like executeStep(), hasRole(), sendEmail(), publishToAnalytics().
When ever these existing APIs are not adequate you have to introduce new API to JS environment.
I will take simple use case to introduce the capability. You have a function call hasRole(user,role) which simple check the given user has particular role or not.
EX: var isAdmin = hasRole(user, ‘admin’);
How it works ?
object “user” has username attribute and hasRole check whether given user has particular role against local userstore.
Limitation is if the given user is federated user, how can you check availability of particular role because there is no presence of the user in local user store ?
In this example I will show you how to add “isUserInRole” function to JavaScript environment which is capable of checking availability particular role for both federated and local users. For sample source code you can refer [4] but I will explain important points one by one.
Point — 01: Obtain JsFunctionRegistry as OSGI service and set into data holder.
@Reference(service = JsFunctionRegistry.class,cardinality = ReferenceCardinality.MANDATORY,policy = ReferencePolicy.DYNAMIC,unbind = “unsetJsFunctionRegistry”)public void setJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) { CustomUserFunctionsServiceHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistry);}public void unsetJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) {CustomUserFunctionsServiceHolder.getInstance().setJsFunctionRegistry(null);}
Point — 02: Implement functional interface
Please refer [5] for sample interface and [6] for implementation.
Point — 03: Register functional interface when you activate the bundle
@Activateprotected void activate(ComponentContext ctxt) {IsUserInRoleFunction isUserInRoleFunction = new IsUserInRoleFunctionImpl();sFunctionRegistry jsFunctionRegistry = CustomUserFunctionsServiceHolder.getInstance().getJsFunctionRegistry(); jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, “isUserInRole”,isUserInRoleFunction);}
How to try it ?

You can clearly see first step is federated authenticator with name XYZ-IDP. In the Script configuration it says execute step 1 mean execute federated authenticator from XYZ-IDP if authenticated user has role “engineer” isUserInRole (user, ‘engineer’) function will return “true”.
[2] https://docs.wso2.com/display/IS570/Adaptive+Authentication+JS+API+Reference
[4] https://github.com/GayanM/org.wso2.carbon.identity.conditional.auth.functions.user.custom
