Search in sources :

Example 11 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class AuthenticationHandler method authenticate.

/**
 * Checks whether a given userName:password combination authenticates correctly against carbon userStore
 * Upon successful authentication returns true, false otherwise
 *
 * @param userName
 * @param password
 * @return
 * @throws RestApiBasicAuthenticationException wraps and throws exceptions occur when trying to authenticate
 *                                             the user
 */
private boolean authenticate(String userName, String password) throws RestApiBasicAuthenticationException {
    boolean authStatus;
    try {
        IdentityService identityService = BPMNOSGIService.getIdentityService();
        authStatus = identityService.checkPassword(userName, password);
        if (!authStatus) {
            return false;
        }
    } catch (BPMNAuthenticationException e) {
        throw new RestApiBasicAuthenticationException(e.getMessage(), e);
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userName);
    String userNameWithTenantDomain = tenantAwareUserName + "@" + tenantDomain;
    RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
    TenantManager mgr = realmService.getTenantManager();
    int tenantId = 0;
    try {
        tenantId = mgr.getTenantId(tenantDomain);
        // tenantId == -1, means an invalid tenant.
        if (tenantId == -1) {
            if (log.isDebugEnabled()) {
                log.debug("Basic authentication request with an invalid tenant : " + userNameWithTenantDomain);
            }
            return false;
        }
    } catch (UserStoreException e) {
        throw new RestApiBasicAuthenticationException("Identity exception thrown while getting tenant ID for user : " + userNameWithTenantDomain, e);
    }
    /* Upon successful authentication existing thread local carbon context
             * is updated to mimic the authenticated user */
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    carbonContext.setUsername(tenantAwareUserName);
    carbonContext.setTenantId(tenantId);
    carbonContext.setTenantDomain(tenantDomain);
    return true;
}
Also used : IdentityService(org.activiti.engine.IdentityService) RestApiBasicAuthenticationException(org.wso2.carbon.bpmn.rest.common.exception.RestApiBasicAuthenticationException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) BPMNAuthenticationException(org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager)

Example 12 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method proceedWithOTP.

/**
 * Proceed with One Time Password.
 *
 * @param response     the HttpServletResponse
 * @param context      the AuthenticationContext
 * @param errorPage    the errorPage
 * @param mobileNumber the mobile number
 * @param queryParams  the queryParams
 * @param username     the Username
 * @throws AuthenticationFailedException
 */
private void proceedWithOTP(HttpServletResponse response, AuthenticationContext context, String errorPage, String mobileNumber, String queryParams, String username) throws AuthenticationFailedException {
    String screenValue;
    Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
    boolean isEnableResendCode = SMSOTPUtils.isEnableResendCode(context, getName());
    String loginPage = getLoginPage(context);
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
    UserRealm userRealm = SMSOTPUtils.getUserRealm(tenantDomain);
    try {
        // One time password is generated and stored in the context.
        OneTimePassword token = new OneTimePassword();
        String secret = OneTimePassword.getRandomNumber(SMSOTPConstants.SECRET_KEY_LENGTH);
        String otpToken = token.generateToken(secret, String.valueOf(SMSOTPConstants.NUMBER_BASE), SMSOTPConstants.NUMBER_DIGIT);
        context.setProperty(SMSOTPConstants.OTP_TOKEN, otpToken);
        if (log.isDebugEnabled()) {
            log.debug("Generated OTP successfully and set to the context.");
        }
        // Get the values of the sms provider related api parameters.
        String smsUrl = authenticatorProperties.get(SMSOTPConstants.SMS_URL);
        String httpMethod = authenticatorProperties.get(SMSOTPConstants.HTTP_METHOD);
        String headerString = authenticatorProperties.get(SMSOTPConstants.HEADERS);
        String payload = authenticatorProperties.get(SMSOTPConstants.PAYLOAD);
        String httpResponse = authenticatorProperties.get(SMSOTPConstants.HTTP_RESPONSE);
        if (!sendRESTCall(context, smsUrl, httpMethod, headerString, payload, httpResponse, mobileNumber, otpToken)) {
            String retryParam;
            context.setProperty(SMSOTPConstants.STATUS_CODE, SMSOTPConstants.UNABLE_SEND_CODE);
            if (context.getProperty(SMSOTPConstants.ERROR_CODE) != null) {
                retryParam = SMSOTPConstants.UNABLE_SEND_CODE_PARAM + context.getProperty(SMSOTPConstants.ERROR_CODE).toString();
            } else {
                retryParam = SMSOTPConstants.UNABLE_SEND_CODE_PARAM + SMSOTPConstants.UNABLE_SEND_CODE_VALUE;
            }
            String redirectUrl = getURL(errorPage, queryParams);
            response.sendRedirect(redirectUrl + SMSOTPConstants.RESEND_CODE + isEnableResendCode + retryParam);
        } else {
            String url = getURL(loginPage, queryParams);
            boolean isUserExists = FederatedAuthenticatorUtil.isUserExistInUserStore(username);
            if (isUserExists) {
                screenValue = getScreenAttribute(context, userRealm, tenantAwareUsername);
                if (screenValue != null) {
                    url = url + SMSOTPConstants.SCREEN_VALUE + screenValue;
                }
            }
            response.sendRedirect(url);
        }
    } catch (IOException e) {
        throw new AuthenticationFailedException("Error while sending the HTTP request. ", e);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Failed to get the user from user store. ", e);
    }
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) IOException(java.io.IOException)

Example 13 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method getScreenValue.

/**
 * Get the screen value for configured screen attribute.
 *
 * @param context the AuthenticationContext
 * @return screenValue
 * @throws AuthenticationFailedException
 */
private String getScreenValue(AuthenticationContext context) throws AuthenticationFailedException {
    String screenValue;
    String username = String.valueOf(context.getProperty(SMSOTPConstants.USER_NAME));
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
    UserRealm userRealm = SMSOTPUtils.getUserRealm(tenantDomain);
    try {
        screenValue = getScreenAttribute(context, userRealm, tenantAwareUsername);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Failed to get the screen attribute for the user " + tenantAwareUsername + " from user store. ", e);
    }
    return screenValue;
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 14 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method getUserRealm.

/**
 * Get the user realm of the logged in user.
 *
 * @param username the Username
 * @return the userRealm
 * @throws AuthenticationFailedException
 */
private UserRealm getUserRealm(String username) throws AuthenticationFailedException {
    UserRealm userRealm = null;
    try {
        if (StringUtils.isNotEmpty(username)) {
            String tenantDomain = MultitenantUtils.getTenantDomain(username);
            int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
            RealmService realmService = IdentityTenantUtil.getRealmService();
            userRealm = realmService.getTenantUserRealm(tenantId);
        }
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Cannot find the user realm. ", e);
    }
    return userRealm;
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 15 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method initiateAuthenticationRequest.

/**
 * Initiate the authentication request.
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException {
    try {
        String username;
        AuthenticatedUser authenticatedUser;
        String mobileNumber;
        String tenantDomain = context.getTenantDomain();
        context.setProperty(SMSOTPConstants.AUTHENTICATION, SMSOTPConstants.AUTHENTICATOR_NAME);
        if (!tenantDomain.equals(SMSOTPConstants.SUPER_TENANT)) {
            IdentityHelperUtil.loadApplicationAuthenticationXMLFromRegistry(context, getName(), tenantDomain);
        }
        FederatedAuthenticatorUtil.setUsernameFromFirstStep(context);
        username = String.valueOf(context.getProperty(SMSOTPConstants.USER_NAME));
        authenticatedUser = (AuthenticatedUser) context.getProperty(SMSOTPConstants.AUTHENTICATED_USER);
        // find the authenticated user.
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug("Authentication failed: Could not find the authenticated user. ");
            }
            throw new AuthenticationFailedException("Authentication failed: Cannot proceed further without identifying the user. ");
        }
        boolean isSMSOTPMandatory = SMSOTPUtils.isSMSOTPMandatory(context, getName());
        boolean isUserExists = FederatedAuthenticatorUtil.isUserExistInUserStore(username);
        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier());
        String errorPage = getErrorPage(context);
        // SMS OTP authentication is mandatory and user doesn't disable SMS OTP claim in user's profile.
        if (isSMSOTPMandatory) {
            if (log.isDebugEnabled()) {
                log.debug("SMS OTP is mandatory. Hence processing in mandatory path");
            }
            processSMSOTPMandatoryCase(context, request, response, queryParams, username, isUserExists);
        } else if (isUserExists && !SMSOTPUtils.isSMSOTPDisableForLocalUser(username, context, getName())) {
            if (context.isRetrying() && !Boolean.parseBoolean(request.getParameter(SMSOTPConstants.RESEND))) {
                checkStatusCode(response, context, queryParams, errorPage);
            } else {
                mobileNumber = getMobileNumber(request, response, context, username, tenantDomain, queryParams);
                if (StringUtils.isNotEmpty(mobileNumber)) {
                    proceedWithOTP(response, context, errorPage, mobileNumber, queryParams, username);
                }
            }
        } else {
            processFirstStepOnly(authenticatedUser, context);
        }
    } catch (SMSOTPException e) {
        throw new AuthenticationFailedException("Failed to get the parameters from authentication xml fie. ", e);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Failed to get the user from User Store. ", e);
    }
}
Also used : AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SMSOTPException(org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

UserStoreException (org.wso2.carbon.user.api.UserStoreException)21 UserRealm (org.wso2.carbon.user.api.UserRealm)10 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)6 RealmService (org.wso2.carbon.user.core.service.RealmService)6 ArrayList (java.util.ArrayList)5 SMSOTPException (org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException)5 ActivitiException (org.activiti.engine.ActivitiException)4 HumanTaskRuntimeException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)4 UserRealm (org.wso2.carbon.user.core.UserRealm)4 UserStoreException (org.wso2.carbon.user.core.UserStoreException)4 IOException (java.io.IOException)3 List (java.util.List)3 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)3 BPMNAuthenticationException (org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException)3 BPMNForbiddenException (org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException)3 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)3 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2