use of org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator in project carbon-identity-framework by wso2.
the class FrameworkServiceComponent method setAuthenticator.
@Reference(name = "application.authenticator", service = ApplicationAuthenticator.class, cardinality = ReferenceCardinality.AT_LEAST_ONE, policy = ReferencePolicy.DYNAMIC, unbind = "unsetAuthenticator")
protected void setAuthenticator(ApplicationAuthenticator authenticator) {
FrameworkServiceDataHolder.getInstance().getAuthenticators().add(authenticator);
Property[] configProperties = null;
List<Property> configurationProperties = authenticator.getConfigurationProperties();
if (configurationProperties == null) {
configurationProperties = new ArrayList<>();
}
if (authenticator instanceof AuthenticationFlowHandler) {
Property handlerProperty = new Property();
handlerProperty.setName(IS_HANDLER);
handlerProperty.setValue(TRUE);
configurationProperties.add(handlerProperty);
}
if (!configurationProperties.isEmpty()) {
configProperties = configurationProperties.toArray(new Property[0]);
}
if ((authenticator instanceof LocalApplicationAuthenticator) || (authenticator instanceof AuthenticationFlowHandler)) {
LocalAuthenticatorConfig localAuthenticatorConfig = new LocalAuthenticatorConfig();
localAuthenticatorConfig.setName(authenticator.getName());
localAuthenticatorConfig.setProperties(configProperties);
localAuthenticatorConfig.setDisplayName(authenticator.getFriendlyName());
localAuthenticatorConfig.setTags(authenticator.getTags());
AuthenticatorConfig fileBasedConfig = getAuthenticatorConfig(authenticator.getName());
localAuthenticatorConfig.setEnabled(fileBasedConfig.isEnabled());
ApplicationAuthenticatorService.getInstance().addLocalAuthenticator(localAuthenticatorConfig);
} else if (authenticator instanceof FederatedApplicationAuthenticator) {
FederatedAuthenticatorConfig federatedAuthenticatorConfig = new FederatedAuthenticatorConfig();
federatedAuthenticatorConfig.setName(authenticator.getName());
federatedAuthenticatorConfig.setProperties(configProperties);
federatedAuthenticatorConfig.setDisplayName(authenticator.getFriendlyName());
federatedAuthenticatorConfig.setTags(authenticator.getTags());
ApplicationAuthenticatorService.getInstance().addFederatedAuthenticator(federatedAuthenticatorConfig);
} else if (authenticator instanceof RequestPathApplicationAuthenticator) {
RequestPathAuthenticatorConfig reqPathAuthenticatorConfig = new RequestPathAuthenticatorConfig();
reqPathAuthenticatorConfig.setName(authenticator.getName());
reqPathAuthenticatorConfig.setProperties(configProperties);
reqPathAuthenticatorConfig.setDisplayName(authenticator.getFriendlyName());
reqPathAuthenticatorConfig.setTags(authenticator.getTags());
AuthenticatorConfig fileBasedConfig = getAuthenticatorConfig(authenticator.getName());
reqPathAuthenticatorConfig.setEnabled(fileBasedConfig.isEnabled());
ApplicationAuthenticatorService.getInstance().addRequestPathAuthenticator(reqPathAuthenticatorConfig);
}
if (log.isDebugEnabled()) {
log.debug("Added application authenticator : " + authenticator.getName());
}
}
use of org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator in project carbon-identity-framework by wso2.
the class DefaultStepHandler method doAuthentication.
protected void doAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, AuthenticatorConfig authenticatorConfig) throws FrameworkException {
SequenceConfig sequenceConfig = context.getSequenceConfig();
int currentStep = context.getCurrentStep();
StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);
ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
if (authenticator == null) {
LOG.error("Authenticator is null for AuthenticatorConfig: " + authenticatorConfig.getName());
return;
}
String idpName = FrameworkConstants.LOCAL_IDP_NAME;
if (context.getExternalIdP() != null && authenticator instanceof FederatedApplicationAuthenticator) {
idpName = context.getExternalIdP().getIdPName();
}
try {
context.setAuthenticatorProperties(FrameworkUtils.getAuthenticatorPropertyMapFromIdP(context.getExternalIdP(), authenticator.getName()));
AuthenticatorFlowStatus status = authenticator.process(request, response, context);
request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status);
if (LOG.isDebugEnabled()) {
LOG.debug(authenticator.getName() + " returned: " + status.toString());
}
if (status == AuthenticatorFlowStatus.INCOMPLETE) {
context.setCurrentAuthenticator(authenticator.getName());
if (LOG.isDebugEnabled()) {
LOG.debug(authenticator.getName() + " is redirecting");
}
return;
}
if (authenticator instanceof FederatedApplicationAuthenticator) {
if (context.getSubject().getUserName() == null) {
// Set subject identifier as the default username for federated users
String authenticatedSubjectIdentifier = context.getSubject().getAuthenticatedSubjectIdentifier();
context.getSubject().setUserName(authenticatedSubjectIdentifier);
}
if (context.getSubject().getFederatedIdPName() == null && context.getExternalIdP() != null) {
// Setting identity provider's name
context.getSubject().setFederatedIdPName(idpName);
}
if (context.getSubject().getTenantDomain() == null) {
// Setting service provider's tenant domain as the default tenant for federated users
String tenantDomain = context.getTenantDomain();
context.getSubject().setTenantDomain(tenantDomain);
}
try {
// Check if the user id is available for the user. If the user id is not available or cannot be
// resolved, UserIdNotFoundException is thrown.
String userId = context.getSubject().getUserId();
if (LOG.isDebugEnabled()) {
LOG.debug("User id is available for user: " + userId);
}
} catch (UserIdNotFoundException e) {
String tenantDomain = context.getSubject().getTenantDomain();
int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
String authenticatedSubjectIdentifier = context.getSubject().getAuthenticatedSubjectIdentifier();
String federatedIdPName = context.getSubject().getFederatedIdPName();
try {
int idpId = UserSessionStore.getInstance().getIdPId(federatedIdPName, tenantId);
String userId = UserSessionStore.getInstance().getFederatedUserId(authenticatedSubjectIdentifier, tenantId, idpId);
try {
if (userId == null) {
userId = UUID.randomUUID().toString();
UserSessionStore.getInstance().storeUserData(userId, authenticatedSubjectIdentifier, tenantId, idpId);
}
} catch (DuplicatedAuthUserException e1) {
String msg = "User authenticated is already persisted. Username: " + authenticatedSubjectIdentifier + " Tenant Domain:" + tenantDomain + " IdP: " + federatedIdPName;
LOG.warn(msg);
if (LOG.isDebugEnabled()) {
LOG.debug(msg, e1);
}
// Since duplicate entry was found, let's try to get the ID again.
userId = UserSessionStore.getInstance().getFederatedUserId(authenticatedSubjectIdentifier, tenantId, idpId);
}
context.getSubject().setUserId(userId);
} catch (UserSessionException e2) {
LOG.error("Error while resolving the user id for federated user.", e2);
}
}
}
AuthenticatedIdPData authenticatedIdPData = getAuthenticatedIdPData(context, idpName);
// store authenticated user
AuthenticatedUser authenticatedUser = context.getSubject();
stepConfig.setAuthenticatedUser(authenticatedUser);
authenticatedIdPData.setUser(authenticatedUser);
authenticatorConfig.setAuthenticatorStateInfo(context.getStateInfo());
stepConfig.setAuthenticatedAutenticator(authenticatorConfig);
// store authenticated idp
stepConfig.setAuthenticatedIdP(idpName);
authenticatedIdPData.setIdpName(idpName);
authenticatedIdPData.addAuthenticator(authenticatorConfig);
// add authenticated idp data to the session wise map
context.getCurrentAuthenticatedIdPs().put(idpName, authenticatedIdPData);
// Add SAML federated idp session index into the authentication step history.
String idpSessionIndex = null;
String parameterName = FEDERATED_IDP_SESSION_ID + idpName;
AuthHistory authHistory = new AuthHistory(authenticator.getName(), idpName);
if (context.getParameters() != null && context.getParameters().containsKey(parameterName)) {
Object idpSessionIndexParamValue = context.getParameter(parameterName);
if (idpSessionIndexParamValue != null) {
idpSessionIndex = idpSessionIndexParamValue.toString();
}
}
if (StringUtils.isNotBlank(context.getCurrentAuthenticator()) && StringUtils.isNotBlank(idpSessionIndex)) {
authHistory.setIdpSessionIndex(idpSessionIndex);
authHistory.setRequestType(context.getRequestType());
}
Serializable startTime = context.getAnalyticsData(FrameworkConstants.AnalyticsData.CURRENT_AUTHENTICATOR_START_TIME);
if (startTime instanceof Long) {
authHistory.setDuration((long) startTime - System.currentTimeMillis());
}
authHistory.setSuccess(true);
context.addAuthenticationStepHistory(authHistory);
String initiator = null;
if (stepConfig.getAuthenticatedUser() != null) {
initiator = stepConfig.getAuthenticatedUser().toFullQualifiedUsername();
}
String data = "Step: " + stepConfig.getOrder() + ", IDP: " + stepConfig.getAuthenticatedIdP() + ", Authenticator:" + stepConfig.getAuthenticatedAutenticator().getName();
if (!isLegacyAuditLogsDisabled()) {
audit.info(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, SUCCESS));
}
} catch (InvalidCredentialsException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("A login attempt was failed due to invalid credentials", e);
}
String data = "Step: " + stepConfig.getOrder() + ", IDP: " + idpName + ", Authenticator:" + authenticatorConfig.getName();
String initiator = null;
if (e.getUser() != null) {
initiator = e.getUser().toFullQualifiedUsername();
} else if (context.getSubject() != null) {
initiator = context.getSubject().toFullQualifiedUsername();
}
if (!isLegacyAuditLogsDisabled()) {
audit.warn(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, FAILURE));
}
handleFailedAuthentication(request, response, context, authenticatorConfig, e.getUser());
} catch (AuthenticationFailedException e) {
IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg();
if (errorContext != null) {
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (!IdentityCoreConstants.ADMIN_FORCED_USER_PASSWORD_RESET_VIA_OTP_ERROR_CODE.equals(errorContext.getErrorCode()) && !(rootCause instanceof UserStoreClientException) && !IdentityCoreConstants.USER_ACCOUNT_LOCKED_ERROR_CODE.equals(errorContext.getErrorCode()) && !IdentityCoreConstants.USER_ACCOUNT_DISABLED_ERROR_CODE.equals(errorContext.getErrorCode()) && !IdentityCoreConstants.USER_ACCOUNT_NOT_CONFIRMED_ERROR_CODE.equals(errorContext.getErrorCode())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Authentication failed exception!", e);
}
LOG.error("Authentication failed exception! " + e.getMessage());
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Authentication failed exception!", e);
}
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Authentication failed exception!", e);
}
LOG.error("Authentication failed exception! " + e.getMessage());
}
String data = "Step: " + stepConfig.getOrder() + ", IDP: " + idpName + ", Authenticator:" + authenticatorConfig.getName();
String initiator = null;
if (e.getUser() != null) {
initiator = e.getUser().toFullQualifiedUsername();
} else if (context.getSubject() != null) {
initiator = context.getSubject().toFullQualifiedUsername();
}
if (!isLegacyAuditLogsDisabled()) {
audit.warn(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, FAILURE));
}
handleFailedAuthentication(request, response, context, authenticatorConfig, e.getUser());
} catch (LogoutFailedException e) {
throw new FrameworkException(e.getMessage(), e);
}
stepConfig.setCompleted(true);
}
use of org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator in project carbon-identity-framework by wso2.
the class JITProvisioningPostAuthenticationHandler method handleResponseFlow.
/**
* This method is used to handle response flow, after going through password provisioning.
*
* @param request HttpServlet request.
* @param context Authentication context
* @return Status of PostAuthnHandler flow.
* @throws PostAuthenticationFailedException Post Authentication Failed Exception
*/
@SuppressWarnings("unchecked")
private PostAuthnHandlerFlowStatus handleResponseFlow(HttpServletRequest request, AuthenticationContext context) throws PostAuthenticationFailedException {
SequenceConfig sequenceConfig = context.getSequenceConfig();
for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
StepConfig stepConfig = entry.getValue();
AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
if (authenticator instanceof FederatedApplicationAuthenticator) {
String externalIdPConfigName = stepConfig.getAuthenticatedIdP();
ExternalIdPConfig externalIdPConfig = getExternalIdpConfig(externalIdPConfigName, context);
context.setExternalIdP(externalIdPConfig);
if (externalIdPConfig != null && externalIdPConfig.isProvisioningEnabled()) {
if (log.isDebugEnabled()) {
log.debug("JIT provisioning response flow has hit for the IDP " + externalIdPConfigName + " " + "for the user, " + sequenceConfig.getAuthenticatedUser().getLoggableUserId());
}
final Map<String, String> localClaimValues;
Object unfilteredLocalClaimValues = context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
localClaimValues = unfilteredLocalClaimValues == null ? new HashMap<>() : (Map<String, String>) unfilteredLocalClaimValues;
Map<String, String> combinedLocalClaims = getCombinedClaims(request, localClaimValues, context);
if (externalIdPConfig.isPasswordProvisioningEnabled()) {
combinedLocalClaims.put(FrameworkConstants.PASSWORD, request.getParameter(FrameworkConstants.PASSWORD));
}
String username = getUsernameFederatedUser(stepConfig, sequenceConfig, externalIdPConfigName, context, localClaimValues, externalIdPConfig);
if (context.getProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED) != null) {
username = request.getParameter(FrameworkConstants.USERNAME);
try {
/*
Checks whether the provided user is already existing in the system. If so an exception
will be thrown.
*/
UserRealm realm = getUserRealm(context.getTenantDomain());
UserStoreManager userStoreManager = getUserStoreManager(context.getExternalIdP().getProvisioningUserStoreId(), realm, username);
String sanitizedUserName = UserCoreUtil.removeDomainFromName(MultitenantUtils.getTenantAwareUsername(username));
if (userStoreManager.isExistingUser(sanitizedUserName)) {
// Logging the error because the thrown exception is handled in the UI.
log.error(ErrorMessages.USER_ALREADY_EXISTS_ERROR.getCode() + " - " + ErrorMessages.USER_ALREADY_EXISTS_ERROR.getMessage());
handleExceptions(ErrorMessages.USER_ALREADY_EXISTS_ERROR.getMessage(), "provided.username.already.exists", null);
}
} catch (UserStoreException e) {
handleExceptions(ErrorMessages.ERROR_WHILE_CHECKING_USERNAME_EXISTENCE.getMessage(), "error.user.existence", e);
}
}
callDefaultProvisioningHandler(username, context, externalIdPConfig, combinedLocalClaims, stepConfig);
handleConsents(request, stepConfig, context.getTenantDomain());
}
}
}
return SUCCESS_COMPLETED;
}
use of org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator in project carbon-identity-framework by wso2.
the class JITProvisioningPostAuthenticationHandler method handleRequestFlow.
/**
* To handle the request flow of the post authentication handler.
*
* @param response HttpServlet response.
* @param context Authentication context
* @return Status of this post authentication handler flow.
* @throws PostAuthenticationFailedException Exception that will be thrown in case of failure.
*/
@SuppressWarnings("unchecked")
private PostAuthnHandlerFlowStatus handleRequestFlow(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
String retryURL = ConfigurationFacade.getInstance().getAuthenticationEndpointRetryURL();
SequenceConfig sequenceConfig = context.getSequenceConfig();
for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
StepConfig stepConfig = entry.getValue();
AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
if (authenticatorConfig == null) {
// ex: Different authentication sequences evaluated by the script
continue;
}
ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
if (authenticator instanceof FederatedApplicationAuthenticator) {
String externalIdPConfigName = stepConfig.getAuthenticatedIdP();
ExternalIdPConfig externalIdPConfig = getExternalIdpConfig(externalIdPConfigName, context);
context.setExternalIdP(externalIdPConfig);
Map<String, String> localClaimValues;
if (stepConfig.isSubjectAttributeStep()) {
localClaimValues = (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
} else {
localClaimValues = getLocalClaimValuesOfIDPInNonAttributeSelectionStep(context, stepConfig, externalIdPConfig);
}
if (localClaimValues == null || localClaimValues.size() == 0) {
Map<ClaimMapping, String> userAttributes = stepConfig.getAuthenticatedUser().getUserAttributes();
localClaimValues = FrameworkUtils.getClaimMappings(userAttributes, false);
}
if (externalIdPConfig != null && externalIdPConfig.isProvisioningEnabled()) {
if (localClaimValues == null) {
localClaimValues = new HashMap<>();
}
String associatedLocalUser = getLocalUserAssociatedForFederatedIdentifier(stepConfig.getAuthenticatedIdP(), stepConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier(), context.getTenantDomain());
String username = associatedLocalUser;
// If associatedLocalUser is null, that means relevant association not exist already.
if (StringUtils.isEmpty(associatedLocalUser)) {
if (log.isDebugEnabled()) {
log.debug(sequenceConfig.getAuthenticatedUser().getLoggableUserId() + " coming from " + externalIdPConfig.getIdPName() + " do not have a local account, hence redirecting" + " to the UI to sign up.");
}
if (externalIdPConfig.isPromptConsentEnabled()) {
username = getUsernameFederatedUser(stepConfig, sequenceConfig, externalIdPConfigName, context, localClaimValues, externalIdPConfig);
redirectToAccountCreateUI(externalIdPConfig, context, localClaimValues, response, username, request);
// Set the property to make sure the request is a returning one.
context.setProperty(FrameworkConstants.PASSWORD_PROVISION_REDIRECTION_TRIGGERED, true);
return PostAuthnHandlerFlowStatus.INCOMPLETE;
}
}
if (StringUtils.isEmpty(username)) {
username = getUsernameFederatedUser(stepConfig, sequenceConfig, externalIdPConfigName, context, localClaimValues, externalIdPConfig);
}
if (StringUtils.isNotBlank(associatedLocalUser)) {
// Check if the associated local account is locked.
if (isAccountLocked(username, context.getTenantDomain())) {
if (log.isDebugEnabled()) {
log.debug(String.format("The account is locked for the user: %s in the " + "tenant domain: %s ", username, context.getTenantDomain()));
}
String retryParam = "&authFailure=true&authFailureMsg=error.user.account.locked&errorCode=" + UserCoreConstants.ErrorCode.USER_IS_LOCKED;
handleAccountLockLoginFailure(retryURL, context, response, retryParam);
return PostAuthnHandlerFlowStatus.INCOMPLETE;
}
// Check if the associated local account is disabled.
if (isAccountDisabled(associatedLocalUser, context.getTenantDomain())) {
if (log.isDebugEnabled()) {
log.debug(String.format("The account is disabled for the user: %s in the " + "tenant domain: %s ", username, context.getTenantDomain()));
}
String retryParam = "&authFailure=true&authFailureMsg=error.user.account.disabled&errorCode=" + IdentityCoreConstants.USER_ACCOUNT_DISABLED_ERROR_CODE;
handleAccountLockLoginFailure(retryURL, context, response, retryParam);
return PostAuthnHandlerFlowStatus.INCOMPLETE;
}
}
if (log.isDebugEnabled()) {
log.debug("User : " + sequenceConfig.getAuthenticatedUser().getLoggableUserId() + " coming from " + externalIdPConfig.getIdPName() + " do have a local account, with the username " + username);
}
callDefaultProvisioningHandler(username, context, externalIdPConfig, localClaimValues, stepConfig);
}
}
}
return SUCCESS_COMPLETED;
}
use of org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator in project carbon-identity-framework by wso2.
the class PostAuthAssociationHandler method handle.
@Override
@SuppressWarnings("unchecked")
public PostAuthnHandlerFlowStatus handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
if (!FrameworkUtils.isStepBasedSequenceHandlerExecuted(context)) {
return SUCCESS_COMPLETED;
}
SequenceConfig sequenceConfig = context.getSequenceConfig();
for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
StepConfig stepConfig = entry.getValue();
AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
if (authenticatorConfig == null) {
// ex: Different authentication sequences evaluated by the script
continue;
}
ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
if (authenticator instanceof FederatedApplicationAuthenticator) {
if (stepConfig.isSubjectIdentifierStep()) {
if (log.isDebugEnabled()) {
log.debug(authenticator.getName() + " has been set up for subject identifier step.");
}
/*
If AlwaysSendMappedLocalSubjectId is selected, need to get the local user associated with the
federated idp.
*/
String associatedLocalUserName = null;
if (sequenceConfig.getApplicationConfig().isAlwaysSendMappedLocalSubjectId()) {
associatedLocalUserName = getUserNameAssociatedWith(context, stepConfig);
}
if (StringUtils.isNotEmpty(associatedLocalUserName)) {
if (log.isDebugEnabled()) {
log.debug("AlwaysSendMappedLocalSubjectID is selected in service provider level, " + "equavlent local user : " + associatedLocalUserName);
}
setAssociatedLocalUserToContext(associatedLocalUserName, context, stepConfig);
}
}
}
}
return SUCCESS_COMPLETED;
}
Aggregations