use of org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException 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.exception.LogoutFailedException in project carbon-identity-framework by wso2.
the class DefaultLogoutRequestHandler method handle.
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
if (log.isTraceEnabled()) {
log.trace("Inside handle()");
}
SequenceConfig sequenceConfig = context.getSequenceConfig();
// Retrieve session information from cache.
SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), context.getLoginTenantDomain());
ExternalIdPConfig externalIdPConfig = null;
// Remove the session related information from the session tables.
clearUserSessionData(request);
if (FrameworkServiceDataHolder.getInstance().getAuthnDataPublisherProxy() != null && FrameworkServiceDataHolder.getInstance().getAuthnDataPublisherProxy().isEnabled(context) && sessionContext != null) {
Object authenticatedUserObj = sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
AuthenticatedUser authenticatedUser = new AuthenticatedUser();
if (authenticatedUserObj instanceof AuthenticatedUser) {
authenticatedUser = (AuthenticatedUser) authenticatedUserObj;
}
FrameworkUtils.publishSessionEvent(context.getSessionIdentifier(), request, context, sessionContext, authenticatedUser, FrameworkConstants.AnalyticsAttributes.SESSION_TERMINATE);
}
// Remove federated authentication session details from the database.
if (sessionContext != null && StringUtils.isNotBlank(context.getSessionIdentifier()) && sessionContext.getSessionAuthHistory() != null && sessionContext.getSessionAuthHistory().getHistory() != null) {
for (AuthHistory authHistory : sessionContext.getSessionAuthHistory().getHistory()) {
if (FED_AUTH_NAME.equals(authHistory.getAuthenticatorName())) {
try {
UserSessionStore.getInstance().removeFederatedAuthSessionInfo(context.getSessionIdentifier());
break;
} catch (UserSessionException e) {
throw new FrameworkException("Error while deleting federated authentication session details for" + " the session context key :" + context.getSessionIdentifier(), e);
}
}
}
}
// remove SessionContext from the cache and auth cookie before sending logout request to federated IDP,
// without waiting till a logout response is received from federated IDP.
// remove the SessionContext from the cache
FrameworkUtils.removeSessionContextFromCache(context.getSessionIdentifier(), context.getLoginTenantDomain());
// remove the cookie
if (IdentityTenantUtil.isTenantedSessionsEnabled()) {
FrameworkUtils.removeAuthCookie(request, response, context.getLoginTenantDomain());
} else {
FrameworkUtils.removeAuthCookie(request, response);
}
if (context.isPreviousSessionFound()) {
// if this is the start of the logout sequence
if (context.getCurrentStep() == 0) {
context.setCurrentStep(1);
}
int stepCount = sequenceConfig.getStepMap().size();
while (context.getCurrentStep() <= stepCount) {
int currentStep = context.getCurrentStep();
StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);
AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
if (authenticatorConfig == null) {
authenticatorConfig = sequenceConfig.getAuthenticatedReqPathAuthenticator();
}
ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
String idpName = stepConfig.getAuthenticatedIdP();
// TODO: Need to fix occurrences where idPName becomes "null"
if ((idpName == null || "null".equalsIgnoreCase(idpName) || idpName.isEmpty()) && sequenceConfig.getAuthenticatedReqPathAuthenticator() != null) {
idpName = FrameworkConstants.LOCAL_IDP_NAME;
}
try {
externalIdPConfig = ConfigurationFacade.getInstance().getIdPConfigByName(idpName, context.getTenantDomain());
context.setExternalIdP(externalIdPConfig);
context.setAuthenticatorProperties(FrameworkUtils.getAuthenticatorPropertyMapFromIdP(externalIdPConfig, authenticator.getName()));
if (authenticatorConfig.getAuthenticatorStateInfo() != null) {
context.setStateInfo(authenticatorConfig.getAuthenticatorStateInfo());
} else {
context.setStateInfo(getStateInfoFromPreviousAuthenticatedIdPs(idpName, authenticatorConfig.getName(), context));
}
AuthenticatorFlowStatus status = authenticator.process(request, response, context);
request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status);
if (!status.equals(AuthenticatorFlowStatus.INCOMPLETE)) {
// TODO what if logout fails. this is an edge case
currentStep++;
context.setCurrentStep(currentStep);
continue;
}
// sends the logout request to the external IdP
return;
} catch (AuthenticationFailedException | LogoutFailedException e) {
throw new FrameworkException("Exception while handling logout request", e);
} catch (IdentityProviderManagementException e) {
log.error("Exception while getting IdP by name", e);
}
}
}
try {
sendResponse(request, response, context, true);
} catch (ServletException | IOException e) {
throw new FrameworkException(e.getMessage(), e);
}
}
use of org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticatorTest method testProcessWithLogout.
@Test
public void testProcessWithLogout() throws AuthenticationFailedException, LogoutFailedException {
mockStatic(FederatedAuthenticatorUtil.class);
mockStatic(SMSOTPUtils.class);
mockStatic(FrameworkUtils.class);
when(context.isLogoutRequest()).thenReturn(false);
when(httpServletRequest.getParameter(SMSOTPConstants.CODE)).thenReturn("");
context.setTenantDomain("carbon.super");
AuthenticatedUser authenticatedUser = new AuthenticatedUser();
authenticatedUser.setAuthenticatedSubjectIdentifier("admin");
authenticatedUser.setUserName("testUser");
authenticatedUser.setUserStoreDomain("secondary");
context.setProperty(SMSOTPConstants.SENT_OTP_TOKEN_TIME, 1608101321322l);
when((AuthenticatedUser) context.getProperty(SMSOTPConstants.AUTHENTICATED_USER)).thenReturn(authenticatedUser);
FederatedAuthenticatorUtil.setUsernameFromFirstStep(context);
when(SMSOTPUtils.isSMSOTPMandatory(context)).thenReturn(true);
when(SMSOTPUtils.getErrorPageFromXMLFile(context)).thenReturn(SMSOTPConstants.ERROR_PAGE);
when(SMSOTPUtils.isSendOTPDirectlyToMobile(context)).thenReturn(false);
when(FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier())).thenReturn(null);
when(SMSOTPUtils.getBackupCode(context)).thenReturn("false");
AuthenticatorFlowStatus status = spy.process(httpServletRequest, httpServletResponse, context);
Assert.assertEquals(status, AuthenticatorFlowStatus.INCOMPLETE);
}
use of org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticatorTest method testProcessWithLogoutTrue.
@Test
public void testProcessWithLogoutTrue() throws AuthenticationFailedException, LogoutFailedException {
when(context.isLogoutRequest()).thenReturn(true);
AuthenticatorFlowStatus status = smsotpAuthenticator.process(httpServletRequest, httpServletResponse, context);
Assert.assertEquals(status, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
}
use of org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException in project carbon-identity-framework by wso2.
the class DefaultRequestPathBasedSequenceHandler method handle.
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
if (log.isDebugEnabled()) {
log.debug("Executing the Request Path Authentication...");
}
SequenceConfig seqConfig = context.getSequenceConfig();
List<AuthenticatorConfig> reqPathAuthenticators = seqConfig.getReqPathAuthenticators();
for (AuthenticatorConfig reqPathAuthenticator : reqPathAuthenticators) {
ApplicationAuthenticator authenticator = reqPathAuthenticator.getApplicationAuthenticator();
if (log.isDebugEnabled()) {
log.debug("Executing " + authenticator.getName());
}
if (authenticator.canHandle(request)) {
if (log.isDebugEnabled()) {
log.debug(authenticator.getName() + " can handle the request");
}
try {
AuthenticatorFlowStatus status = authenticator.process(request, response, context);
request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status);
if (log.isDebugEnabled()) {
log.debug(authenticator.getName() + ".authenticate() returned: " + status.toString());
}
AuthenticatedUser authenticatedUser = context.getSubject();
seqConfig.setAuthenticatedUser(authenticatedUser);
if (log.isDebugEnabled()) {
if (authenticatedUser != null) {
log.debug("Authenticated User: " + authenticatedUser.getAuthenticatedSubjectIdentifier());
log.debug("Authenticated User Tenant Domain: " + authenticatedUser.getTenantDomain());
} else {
log.debug("Authenticated User is NULL.");
}
}
AuthenticatedIdPData authenticatedIdPData = new AuthenticatedIdPData();
// store authenticated user
authenticatedIdPData.setUser(authenticatedUser);
// store authenticated idp
authenticatedIdPData.setIdpName(FrameworkConstants.LOCAL_IDP_NAME);
reqPathAuthenticator.setAuthenticatorStateInfo(context.getStateInfo());
authenticatedIdPData.setAuthenticator(reqPathAuthenticator);
seqConfig.setAuthenticatedReqPathAuthenticator(reqPathAuthenticator);
context.getCurrentAuthenticatedIdPs().put(FrameworkConstants.LOCAL_IDP_NAME, authenticatedIdPData);
handlePostAuthentication(request, response, context, authenticatedIdPData);
context.addAuthenticationStepHistory(new AuthHistory(authenticator.getName(), authenticatedIdPData.getIdpName()));
} catch (InvalidCredentialsException e) {
if (log.isDebugEnabled()) {
log.debug("A login attempt was failed due to invalid credentials", e);
}
context.setRequestAuthenticated(false);
} catch (AuthenticationFailedException e) {
log.error(e.getMessage(), e);
context.setRequestAuthenticated(false);
} catch (LogoutFailedException e) {
throw new FrameworkException(e.getMessage(), e);
}
context.getSequenceConfig().setCompleted(true);
return;
}
}
}
Aggregations