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");
}
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);
}
}
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;
}
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;
}
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;
}
Aggregations