use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator 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.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class DefaultStepHandler method getRedirectUrl.
private String getRedirectUrl(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, String authenticatorNames, String showAuthFailureReason, String retryParam, String loginPage) throws IOException, URISyntaxException {
IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg();
IdentityUtil.clearIdentityErrorMsg();
retryParam = handleIdentifierFirstLogin(context, retryParam);
String otp = (String) context.getProperty(FrameworkConstants.PASSWORD_PROPERTY);
context.getProperties().remove(FrameworkConstants.PASSWORD_PROPERTY);
// If recaptcha is enabled and the Basic Authenticator is in the authenticator list for this page, the recaptcha
// params set by the Basic Authenticator need to be added to new URL generated for the multi option page.
// Currently, there is no method to check whether recaptcha has been enabled without manually reading the
// captcha-config.properties file. Hence, this fragment is always executed without the check, but will not
// alter the final URL if recaptcha is not enabled. This filters out the recaptcha params from the redirect
// URL previously set by an authenticator and generates a query string to be appended to the new redirect URL.
StringBuilder reCaptchaParamString = new StringBuilder("");
StringBuilder errorParamString = new StringBuilder("");
String basicAuthRedirectUrl = ((CommonAuthResponseWrapper) response).getRedirectURL();
if (StringUtils.isNotBlank(basicAuthRedirectUrl)) {
List<NameValuePair> queryParameters = new URIBuilder(basicAuthRedirectUrl).getQueryParams();
List<NameValuePair> reCaptchaParameters = queryParameters.stream().filter(param -> FrameworkConstants.RECAPTCHA_API_PARAM.equals(param.getName()) || FrameworkConstants.RECAPTCHA_KEY_PARAM.equals(param.getName()) || FrameworkConstants.RECAPTCHA_PARAM.equals(param.getName()) || FrameworkConstants.RECAPTCHA_RESEND_CONFIRMATION_PARAM.equals(param.getName())).collect(Collectors.toList());
for (NameValuePair reCaptchaParam : reCaptchaParameters) {
reCaptchaParamString.append("&").append(reCaptchaParam.getName()).append("=").append(reCaptchaParam.getValue());
}
if (errorContext == null) {
List<NameValuePair> errorContextParams = queryParameters.stream().filter(param -> FrameworkConstants.ERROR_CODE.equals(param.getName()) || FrameworkConstants.LOCK_REASON.equals(param.getName()) || FrameworkConstants.REMAINING_ATTEMPTS.equals(param.getName()) || FrameworkConstants.FAILED_USERNAME.equals(param.getName())).collect(Collectors.toList());
if (errorContextParams.size() > 0) {
for (NameValuePair errorParams : errorContextParams) {
errorParamString.append("&").append(errorParams.getName()).append("=").append(errorParams.getValue());
}
}
}
}
if (showAuthFailureReason != null && "true".equals(showAuthFailureReason)) {
if (errorContext != null) {
String errorCode = errorContext.getErrorCode();
String reason = null;
if (errorCode.contains(":")) {
String[] errorCodeReason = errorCode.split(":", 2);
if (errorCodeReason.length > 1) {
errorCode = errorCodeReason[0];
reason = errorCodeReason[1];
}
}
int remainingAttempts = errorContext.getMaximumLoginAttempts() - errorContext.getFailedLoginAttempts();
if (LOG.isDebugEnabled()) {
StringBuilder debugString = new StringBuilder();
debugString.append("Identity error message context is not null. Error details are as follows.");
debugString.append("errorCode : " + errorCode + "\n");
debugString.append("username : " + request.getParameter("username") + "\n");
debugString.append("remainingAttempts : " + remainingAttempts);
LOG.debug(debugString.toString());
}
if (UserCoreConstants.ErrorCode.INVALID_CREDENTIAL.equals(errorCode)) {
retryParam = retryParam + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&remainingAttempts=" + remainingAttempts;
return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
} else if (UserCoreConstants.ErrorCode.USER_IS_LOCKED.equals(errorCode)) {
String redirectURL;
if (remainingAttempts == 0) {
if (StringUtils.isBlank(reason)) {
redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&remainingAttempts=0" + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString;
} else {
redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&lockedReason=" + reason + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&remainingAttempts=0" + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString;
}
} else {
if (StringUtils.isBlank(reason)) {
redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString;
} else {
redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&lockedReason=" + reason + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
}
}
return redirectURL;
} else if (IdentityCoreConstants.USER_ACCOUNT_NOT_CONFIRMED_ERROR_CODE.equals(errorCode)) {
retryParam = "&authFailure=true&authFailureMsg=account.confirmation.pending";
String username = request.getParameter("username");
Object domain = IdentityUtil.threadLocalProperties.get().get(RE_CAPTCHA_USER_DOMAIN);
if (domain != null) {
username = IdentityUtil.addDomainToName(username, domain.toString());
}
retryParam = retryParam + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(username, "UTF-8");
return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
} else if (IdentityCoreConstants.USER_INVALID_CREDENTIALS.equals(errorCode)) {
retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
String username = request.getParameter("username");
Object domain = IdentityUtil.threadLocalProperties.get().get(RE_CAPTCHA_USER_DOMAIN);
if (domain != null) {
username = IdentityUtil.addDomainToName(username, domain.toString());
}
retryParam = retryParam + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(username, "UTF-8");
return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
} else if (IdentityCoreConstants.ADMIN_FORCED_USER_PASSWORD_RESET_VIA_OTP_ERROR_CODE.equals(errorCode)) {
String username = request.getParameter("username");
return response.encodeRedirectURL(("accountrecoveryendpoint/confirmrecovery.do?" + context.getContextIdIncludedQueryParams())) + "&username=" + URLEncoder.encode(username, "UTF-8") + "&confirmation=" + otp + reCaptchaParamString.toString();
} else {
if (StringUtils.isNotBlank(retryParam) && StringUtils.isNotBlank(reason)) {
retryParam = "&authFailure=true&authFailureMsg=" + URLEncoder.encode(reason, "UTF-8");
}
retryParam += "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8");
return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
}
} else {
return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString() + errorParamString;
}
} else {
String errorCode = errorContext != null ? errorContext.getErrorCode() : null;
if (UserCoreConstants.ErrorCode.USER_IS_LOCKED.equals(errorCode)) {
String redirectURL;
redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
return redirectURL;
} else if (IdentityCoreConstants.ADMIN_FORCED_USER_PASSWORD_RESET_VIA_OTP_ERROR_CODE.equals(errorCode)) {
String username = request.getParameter("username");
return response.encodeRedirectURL(("accountrecoveryendpoint/confirmrecovery.do?" + context.getContextIdIncludedQueryParams())) + "&username=" + URLEncoder.encode(username, "UTF-8") + "&confirmation=" + otp + reCaptchaParamString.toString();
} else {
return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
}
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class ApplicationInitializer method initEntitlementAuthenticatorRegistry.
private void initEntitlementAuthenticatorRegistry() {
EntitlementAuthenticatorRegistry entitlementAuthRegistry = EntitlementAuthenticatorRegistry.getInstance();
if (entitlementAuthRegistry != null) {
// set authenticators after building auth config
EntitlementAuthConfigReader configReader = new EntitlementAuthConfigReader();
List<EntitlementAuthenticationHandler> entitlementAuthenticators = configReader.buildEntitlementAuthenticators();
if (entitlementAuthenticators != null && !entitlementAuthenticators.isEmpty()) {
for (EntitlementAuthenticationHandler entitlementAuthenticator : entitlementAuthenticators) {
entitlementAuthRegistry.setAuthenticator(entitlementAuthenticator);
}
} else {
// initialize default basic auth authenticator & OAuth authenticator and set it in the auth registry.
BasicAuthHandler basicAuthHandler = new BasicAuthHandler();
basicAuthHandler.setDefaultPriority();
entitlementAuthRegistry.setAuthenticator(basicAuthHandler);
}
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class JITProvisioningPostAuthenticationHandler method getLocalClaimValuesOfIDPInNonAttributeSelectionStep.
/**
* Uses to get local claim values of an authenticated user from an IDP in non attribute selection steps.
*
* @param context Authentication Context.
* @param stepConfig Current step configuration.
* @param externalIdPConfig Identity providers config.
* @return Mapped federated user values to local claims.
* @throws PostAuthenticationFailedException Post Authentication failed exception.
*/
private Map<String, String> getLocalClaimValuesOfIDPInNonAttributeSelectionStep(AuthenticationContext context, StepConfig stepConfig, ExternalIdPConfig externalIdPConfig) throws PostAuthenticationFailedException {
boolean useDefaultIdpDialect = externalIdPConfig.useDefaultLocalIdpDialect();
ApplicationAuthenticator authenticator = stepConfig.getAuthenticatedAutenticator().getApplicationAuthenticator();
String idPStandardDialect = authenticator.getClaimDialectURI();
Map<ClaimMapping, String> extAttrs = stepConfig.getAuthenticatedUser().getUserAttributes();
Map<String, String> originalExternalAttributeValueMap = FrameworkUtils.getClaimMappings(extAttrs, false);
Map<String, String> claimMapping = new HashMap<>();
Map<String, String> localClaimValues = new HashMap<>();
if (useDefaultIdpDialect && StringUtils.isNotBlank(idPStandardDialect)) {
try {
claimMapping = ClaimMetadataHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(idPStandardDialect, originalExternalAttributeValueMap.keySet(), context.getTenantDomain(), true);
} catch (ClaimMetadataException e) {
throw new PostAuthenticationFailedException(ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getCode(), ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getMessage(), e);
}
} else {
ClaimMapping[] customClaimMapping = context.getExternalIdP().getClaimMappings();
for (ClaimMapping externalClaim : customClaimMapping) {
if (originalExternalAttributeValueMap.containsKey(externalClaim.getRemoteClaim().getClaimUri())) {
claimMapping.put(externalClaim.getLocalClaim().getClaimUri(), externalClaim.getRemoteClaim().getClaimUri());
}
}
}
if (claimMapping != null && claimMapping.size() > 0) {
for (Map.Entry<String, String> entry : claimMapping.entrySet()) {
if (originalExternalAttributeValueMap.containsKey(entry.getValue()) && originalExternalAttributeValueMap.get(entry.getValue()) != null) {
localClaimValues.put(entry.getKey(), originalExternalAttributeValueMap.get(entry.getValue()));
}
}
}
return localClaimValues;
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator 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;
}
Aggregations