Search in sources :

Example 1 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.

the class JsAuthenticatedUser method getLocalRoles.

private String[] getLocalRoles() {
    if (idp == null || FrameworkConstants.LOCAL.equals(idp)) {
        RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
        int usersTenantId = IdentityTenantUtil.getTenantId(getWrapped().getTenantDomain());
        try {
            UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
            List<String> roleListOfUser = ((AbstractUserStoreManager) userRealm.getUserStoreManager()).getRoleListOfUserWithID(getWrapped().getUserId());
            return roleListOfUser.toArray(new String[0]);
        } catch (UserStoreException e) {
            LOG.error("Error when getting role list of user: " + getWrapped(), e);
        } catch (UserIdNotFoundException e) {
            LOG.error("User id is not available for user: " + getWrapped().getLoggableUserId(), e);
        }
    }
    return ArrayUtils.EMPTY_STRING_ARRAY;
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 2 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.

the class JsClaims method getLocalUserClaim.

/**
 * Get the local user claim value specified by the Claim URI.
 *
 * @param claimUri Local claim URI
 * @return Claim value of the given claim URI for the local user if available. Null Otherwise.
 */
private String getLocalUserClaim(String claimUri) {
    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimValues = ((AbstractUserStoreManager) userRealm.getUserStoreManager()).getUserClaimValuesWithID(authenticatedUser.getUserId(), new String[] { claimUri }, null);
        return claimValues.get(claimUri);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when getting claim : %s of user: %s", claimUri, authenticatedUser), e);
    } catch (UserIdNotFoundException e) {
        LOG.error("User id is not available for the user: " + authenticatedUser.getLoggableUserId(), e);
    }
    return null;
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 3 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException 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);
}
Also used : Serializable(java.io.Serializable) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) DuplicatedAuthUserException(org.wso2.carbon.identity.application.authentication.framework.exception.DuplicatedAuthUserException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) LogoutFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityErrorMsgContext(org.wso2.carbon.identity.core.model.IdentityErrorMsgContext) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) InvalidCredentialsException(org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

Example 4 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.

the class DefaultRequestCoordinator method isUserAllowedToLogin.

/**
 * Checks whether AuthenticatedUser object contains a valid user for authentication.
 * Returns false if user verification is failed.
 *
 * @param user
 * @return boolean
 * @throws FrameworkException
 */
private boolean isUserAllowedToLogin(AuthenticatedUser user) {
    if (user.isFederatedUser()) {
        return true;
    }
    int tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    try {
        UserRealm userRealm = (UserRealm) FrameworkServiceComponent.getRealmService().getTenantUserRealm(tenantId);
        AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) userRealm.getUserStoreManager();
        if (userStoreManager.isExistingUserWithID(user.getUserId())) {
            return !(isUserDisabled(userStoreManager, user) || isUserLocked(userStoreManager, user));
        } else {
            log.error("Trying to authenticate non existing user: " + user.getLoggableUserId());
        }
    } catch (UserStoreException e) {
        log.error("Error while checking existence of user: " + user.getLoggableUserId(), e);
    } catch (FrameworkException e) {
        log.error("Error while validating user: " + user.getLoggableUserId(), e);
    } catch (UserIdNotFoundException e) {
        log.error("User id is not available for user: " + user.getLoggableUserId(), e);
    }
    return false;
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 5 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.

the class DefaultAuthenticationRequestHandler method storeSessionData.

/**
 * Method used to store user and session related data to the database.
 *
 * @param context           {@link AuthenticationContext} object with the authentication request related data
 * @param sessionContextKey of the authenticated session
 */
private void storeSessionData(AuthenticationContext context, String sessionContextKey) throws UserSessionException {
    String subject = context.getSequenceConfig().getAuthenticatedUser().getAuthenticatedSubjectIdentifier();
    String inboundAuth = context.getCallerPath().substring(1);
    int appId = context.getSequenceConfig().getApplicationConfig().getApplicationID();
    for (AuthenticatedIdPData authenticatedIdPData : context.getCurrentAuthenticatedIdPs().values()) {
        AuthenticatedUser user = authenticatedIdPData.getUser();
        try {
            String userId = user.getUserId();
            try {
                if (!UserSessionStore.getInstance().isExistingMapping(userId, sessionContextKey)) {
                    UserSessionStore.getInstance().storeUserSessionData(userId, sessionContextKey);
                }
                /*
                For JIT provisioned users, if AssertIdentity Using Mapped Local Subject Identifier config is enabled in
                the app level, add an entry in the IDN_AUTH_USER_SESSION_MAPPING table with local userId.
                 */
                if (user.isFederatedUser() && context.getSequenceConfig().getApplicationConfig().isMappedSubjectIDSelected()) {
                    String localUserId = FrameworkUtils.resolveUserIdFromUsername(IdentityTenantUtil.getTenantId(user.getTenantDomain()), user.getUserStoreDomain(), user.getUserName());
                    if (StringUtils.isNotEmpty(localUserId) && !UserSessionStore.getInstance().isExistingMapping(localUserId, sessionContextKey)) {
                        UserSessionStore.getInstance().storeUserSessionData(localUserId, sessionContextKey);
                    }
                }
            } catch (UserSessionException e) {
                throw new UserSessionException("Error while storing session data for user: " + user.getLoggableUserId(), e);
            }
        } catch (UserIdNotFoundException e) {
            // the mapping is not stored.
            if (log.isDebugEnabled()) {
                log.debug("A unique user id is not set for the user: " + user.getLoggableUserId() + ". Hence the session information of the user is not stored.");
            }
        }
    }
    if (appId > 0) {
        storeAppSessionData(sessionContextKey, subject, appId, inboundAuth);
    }
}
Also used : UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

Aggregations

UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)29 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)14 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)9 HashMap (java.util.HashMap)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)6 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)6 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)5 ArrayList (java.util.ArrayList)4 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)4 RealmService (org.wso2.carbon.user.core.service.RealmService)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)3 JSONObject (org.json.JSONObject)3 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)3 Timestamp (java.sql.Timestamp)2 Date (java.util.Date)2 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)2 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)2