Search in sources :

Example 1 with UserMgtContext

use of org.wso2.carbon.user.core.model.UserMgtContext in project identity-inbound-auth-oauth by wso2-extensions.

the class PasswordGrantHandler method validateUserCredentials.

private AuthenticatedUser validateUserCredentials(OAuth2AccessTokenReqDTO tokenReq, ServiceProvider serviceProvider) throws IdentityOAuth2Exception {
    boolean isPublishPasswordGrantLoginEnabled = Boolean.parseBoolean(IdentityUtil.getProperty(PUBLISH_PASSWORD_GRANT_LOGIN));
    try {
        // Get the user store preference order supplier.
        UserStorePreferenceOrderSupplier<List<String>> userStorePreferenceOrderSupplier = FrameworkUtils.getUserStorePreferenceOrderSupplier(null, serviceProvider);
        UserMgtContext userMgtContext = new UserMgtContext();
        userMgtContext.setUserStorePreferenceOrderSupplier(userStorePreferenceOrderSupplier);
        if (userStorePreferenceOrderSupplier != null) {
            UserCoreUtil.setUserMgtContextInThreadLocal(userMgtContext);
            if (log.isDebugEnabled()) {
                log.debug("UserMgtContext had been set as the thread local.");
            }
        }
        String username = tokenReq.getResourceOwnerUsername();
        if (!IdentityUtil.isEmailUsernameValidationDisabled()) {
            FrameworkUtils.validateUsername(username);
            username = FrameworkUtils.preprocessUsername(username, serviceProvider);
        }
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
        String userTenantDomain = MultitenantUtils.getTenantDomain(username);
        ResolvedUserResult resolvedUserResult = FrameworkUtils.processMultiAttributeLoginIdentification(tenantAwareUserName, userTenantDomain);
        String userId = null;
        if (resolvedUserResult != null && ResolvedUserResult.UserResolvedStatus.SUCCESS.equals(resolvedUserResult.getResolvedStatus())) {
            tenantAwareUserName = resolvedUserResult.getUser().getUsername();
            userId = resolvedUserResult.getUser().getUserID();
            tokenReq.setResourceOwnerUsername(tenantAwareUserName + "@" + userTenantDomain);
        }
        AbstractUserStoreManager userStoreManager = getUserStoreManager(userTenantDomain);
        AuthenticationResult authenticationResult;
        if (userId != null) {
            authenticationResult = userStoreManager.authenticateWithID(userId, tokenReq.getResourceOwnerPassword());
        } else {
            authenticationResult = userStoreManager.authenticateWithID(UserCoreClaimConstants.USERNAME_CLAIM_URI, tenantAwareUserName, tokenReq.getResourceOwnerPassword(), UserCoreConstants.DEFAULT_PROFILE);
        }
        boolean authenticated = AuthenticationResult.AuthenticationStatus.SUCCESS == authenticationResult.getAuthenticationStatus() && authenticationResult.getAuthenticatedUser().isPresent();
        if (log.isDebugEnabled()) {
            log.debug("user " + tokenReq.getResourceOwnerUsername() + " authenticated: " + authenticated);
        }
        if (authenticated) {
            AuthenticatedUser authenticatedUser = new AuthenticatedUser(authenticationResult.getAuthenticatedUser().get());
            if (isPublishPasswordGrantLoginEnabled) {
                publishAuthenticationData(tokenReq, true, serviceProvider, authenticatedUser);
            }
            return authenticatedUser;
        } else {
            if (isPublishPasswordGrantLoginEnabled) {
                publishAuthenticationData(tokenReq, false, serviceProvider);
            }
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(MultitenantUtils.getTenantDomain(tokenReq.getResourceOwnerUsername()))) {
                throw new IdentityOAuth2Exception("Authentication failed for " + tenantAwareUserName);
            }
            username = tokenReq.getResourceOwnerUsername();
            if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
                // For tenant qualified urls, no need to send fully qualified username in response.
                username = tenantAwareUserName;
            }
            throw new IdentityOAuth2Exception("Authentication failed for " + username);
        }
    } catch (UserStoreClientException e) {
        if (isPublishPasswordGrantLoginEnabled) {
            publishAuthenticationData(tokenReq, false, serviceProvider);
        }
        String message = e.getMessage();
        if (StringUtils.isNotBlank(e.getErrorCode())) {
            message = e.getErrorCode() + " " + e.getMessage();
        }
        throw new IdentityOAuth2Exception(message, e);
    } catch (UserStoreException e) {
        if (isPublishPasswordGrantLoginEnabled) {
            publishAuthenticationData(tokenReq, false, serviceProvider);
        }
        String message = e.getMessage();
        // Sometimes client exceptions are wrapped in the super class.
        // Therefore, checking for possible client exception.
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause instanceof UserStoreClientException) {
            message = rootCause.getMessage();
            String errorCode = ((UserStoreClientException) rootCause).getErrorCode();
            if (StringUtils.isNotBlank(errorCode)) {
                message = errorCode + " " + message;
            }
        }
        if (e.getCause() instanceof IdentityException) {
            IdentityException identityException = (IdentityException) (e.getCause());
            // Set error code to message if available.
            if (StringUtils.isNotBlank(identityException.getErrorCode())) {
                message = identityException.getErrorCode() + " " + e.getMessage();
            }
        }
        throw new IdentityOAuth2Exception(message, e);
    } catch (AuthenticationFailedException e) {
        String message = "Authentication failed for the user: " + tokenReq.getResourceOwnerUsername();
        if (log.isDebugEnabled()) {
            log.debug(message, e);
        }
        throw new IdentityOAuth2Exception(message);
    } finally {
        UserCoreUtil.removeUserMgtContextInThreadLocal();
        if (log.isDebugEnabled()) {
            log.debug("UserMgtContext had been remove from the thread local.");
        }
    }
}
Also used : UserMgtContext(org.wso2.carbon.user.core.model.UserMgtContext) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) IdentityException(org.wso2.carbon.identity.base.IdentityException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AuthenticationResult(org.wso2.carbon.user.core.common.AuthenticationResult) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserStoreException(org.wso2.carbon.user.api.UserStoreException) List(java.util.List) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) ResolvedUserResult(org.wso2.carbon.identity.multi.attribute.login.mgt.ResolvedUserResult)

Example 2 with UserMgtContext

use of org.wso2.carbon.user.core.model.UserMgtContext in project carbon-identity-framework by wso2.

the class DefaultAuthenticationRequestHandler method handle.

/**
 * Executes the authentication flow
 *
 * @param request
 * @param response
 * @throws FrameworkException
 */
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
    if (log.isDebugEnabled()) {
        log.debug("In authentication flow");
    }
    if (context.isReturning()) {
        // if "Deny" or "Cancel" pressed on the login page.
        if (request.getParameter(FrameworkConstants.RequestParams.DENY) != null) {
            handleDenyFromLoginPage(request, response, context);
            return;
        }
        // handle remember-me option from the login page
        handleRememberMeOptionFromLoginPage(request, context);
    }
    int currentStep = context.getCurrentStep();
    // if this is the start of the authentication flow
    if (currentStep == 0) {
        handleSequenceStart(request, response, context);
    }
    SequenceConfig seqConfig = context.getSequenceConfig();
    List<AuthenticatorConfig> reqPathAuthenticators = seqConfig.getReqPathAuthenticators();
    boolean addOrUpdateNonceCookie = false;
    try {
        UserStorePreferenceOrderSupplier<List<String>> userStorePreferenceOrderSupplier = FrameworkUtils.getUserStorePreferenceOrderSupplier(context, null);
        if (userStorePreferenceOrderSupplier != null) {
            // Add the user store preference supplier to the container UserMgtContext.
            UserMgtContext userMgtContext = new UserMgtContext();
            userMgtContext.setUserStorePreferenceOrderSupplier(userStorePreferenceOrderSupplier);
            UserCoreUtil.setUserMgtContextInThreadLocal(userMgtContext);
        }
        // the flow
        if (reqPathAuthenticators != null && !reqPathAuthenticators.isEmpty() && currentStep == 0) {
            // call request path sequence handler
            FrameworkUtils.getRequestPathBasedSequenceHandler().handle(request, response, context);
        }
        // if no request path authenticators or handler returned cannot handle
        if (!context.getSequenceConfig().isCompleted() || (reqPathAuthenticators == null || reqPathAuthenticators.isEmpty())) {
            // To keep track of whether particular request goes through the step based sequence handler.
            context.setProperty(FrameworkConstants.STEP_BASED_SEQUENCE_HANDLER_TRIGGERED, true);
            // Add or Validate session nonce cookie.
            if (isNonceCookieEnabled()) {
                String nonceCookieName = getNonceCookieName(context);
                if (context.isReturning()) {
                    if (validateNonceCookie(request, context)) {
                        addOrUpdateNonceCookie = true;
                    } else {
                        throw new FrameworkException(NONCE_ERROR_CODE, "Session nonce cookie value is not " + "matching " + "for session with sessionDataKey: " + request.getParameter("sessionDataKey"));
                    }
                } else if (context.getProperty(nonceCookieName) == null) {
                    addOrUpdateNonceCookie = true;
                }
            }
            // call step based sequence handler
            FrameworkUtils.getStepBasedSequenceHandler().handle(request, response, context);
        }
    } catch (FrameworkException e) {
        // Remove nonce cookie after authentication failure.
        removeNonceCookie(request, response, context);
        throw e;
    } finally {
        UserCoreUtil.removeUserMgtContextInThreadLocal();
    }
    // handle post authentication
    try {
        handlePostAuthentication(request, response, context);
    } catch (FrameworkException e) {
        // Remove nonce cookie after post authentication failure.
        removeNonceCookie(request, response, context);
        throw e;
    }
    // if flow completed, send response back
    if (canConcludeFlow(context)) {
        // Remove nonce cookie after authentication completion.
        if (addOrUpdateNonceCookie) {
            removeNonceCookie(request, response, context);
        }
        concludeFlow(request, response, context);
    } else if (addOrUpdateNonceCookie) {
        // Update nonce cookie value.
        addNonceCookie(request, response, context);
    }
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) UserMgtContext(org.wso2.carbon.user.core.model.UserMgtContext) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) List(java.util.List) ArrayList(java.util.ArrayList)

Aggregations

List (java.util.List)2 UserMgtContext (org.wso2.carbon.user.core.model.UserMgtContext)2 ArrayList (java.util.ArrayList)1 AuthenticatorConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig)1 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)1 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)1 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)1 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)1 IdentityException (org.wso2.carbon.identity.base.IdentityException)1 ResolvedUserResult (org.wso2.carbon.identity.multi.attribute.login.mgt.ResolvedUserResult)1 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)1 UserStoreException (org.wso2.carbon.user.api.UserStoreException)1 UserStoreClientException (org.wso2.carbon.user.core.UserStoreClientException)1 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)1 AuthenticationResult (org.wso2.carbon.user.core.common.AuthenticationResult)1