Search in sources :

Example 1 with CaptchaServerException

use of org.wso2.carbon.identity.captcha.exception.CaptchaServerException in project identity-governance by wso2-extensions.

the class CaptchaUtil method getClaimValues.

public static Map<String, String> getClaimValues(User user, int tenantId, String[] claimUris) throws CaptchaServerException {
    String username = user.getUserName();
    if (!StringUtils.isBlank(user.getUserStoreDomain()) && !"PRIMARY".equals(user.getUserStoreDomain())) {
        username = IdentityUtil.addDomainToName(user.getUserName(), user.getUserStoreDomain());
    }
    RealmService realmService = CaptchaDataHolder.getInstance().getRealmService();
    UserRealm userRealm;
    try {
        userRealm = (UserRealm) realmService.getTenantUserRealm(tenantId);
    } catch (UserStoreException e) {
        throw new CaptchaServerException("Failed to retrieve user realm from tenant id : " + tenantId, e);
    }
    UserStoreManager userStoreManager;
    try {
        userStoreManager = userRealm.getUserStoreManager();
    } catch (UserStoreException e) {
        throw new CaptchaServerException("Failed to retrieve user store manager.", e);
    }
    Map<String, String> claimValues = null;
    try {
        claimValues = userStoreManager.getUserClaimValues(username, claimUris, UserCoreConstants.DEFAULT_PROFILE);
    } catch (org.wso2.carbon.user.core.UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while retrieving user claims.", e);
        }
    }
    return claimValues;
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager)

Example 2 with CaptchaServerException

use of org.wso2.carbon.identity.captcha.exception.CaptchaServerException in project identity-governance by wso2-extensions.

the class CaptchaUtil method isValidCaptcha.

public static boolean isValidCaptcha(String reCaptchaResponse) throws CaptchaException {
    CloseableHttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build();
    HttpPost httppost = new HttpPost(CaptchaDataHolder.getInstance().getReCaptchaVerifyUrl());
    List<BasicNameValuePair> params = Arrays.asList(new BasicNameValuePair("secret", CaptchaDataHolder.getInstance().getReCaptchaSecretKey()), new BasicNameValuePair("response", reCaptchaResponse));
    httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
    HttpResponse response;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException e) {
        throw new CaptchaServerException("Unable to get the verification response.", e);
    }
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new CaptchaServerException("reCaptcha verification response is not received.");
    }
    try {
        try (InputStream in = entity.getContent()) {
            JsonObject verificationResponse = new JsonParser().parse(IOUtils.toString(in)).getAsJsonObject();
            if (verificationResponse == null || verificationResponse.get("success") == null || !verificationResponse.get("success").getAsBoolean()) {
                throw new CaptchaClientException("reCaptcha verification failed. Please try again.");
            }
        }
    } catch (IOException e) {
        throw new CaptchaServerException("Unable to read the verification response.", e);
    }
    return true;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) CaptchaClientException(org.wso2.carbon.identity.captcha.exception.CaptchaClientException) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) JsonObject(com.google.gson.JsonObject) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) JsonParser(com.google.gson.JsonParser)

Example 3 with CaptchaServerException

use of org.wso2.carbon.identity.captcha.exception.CaptchaServerException in project identity-governance by wso2-extensions.

the class PasswordRecoveryReCaptchaConnector method preValidate.

@Override
public CaptchaPreValidationResponse preValidate(ServletRequest servletRequest, ServletResponse servletResponse) throws CaptchaException {
    CaptchaPreValidationResponse preValidationResponse = new CaptchaPreValidationResponse();
    boolean forgotPasswordRecaptchaEnabled = checkReCaptchaEnabledForForgotPassoword(servletRequest, FORGOT_PASSWORD_RECAPTCHA_ENABLE);
    String pathUrl = ((HttpServletRequest) servletRequest).getRequestURI();
    if (forgotPasswordRecaptchaEnabled && (CaptchaUtil.isPathAvailable(pathUrl, ACCOUNT_SECURITY_QUESTION_URL) || CaptchaUtil.isPathAvailable(pathUrl, ACCOUNT_SECURITY_QUESTIONS_URL) || CaptchaUtil.isPathAvailable(pathUrl, RECOVER_PASSWORD_URL))) {
        preValidationResponse.setCaptchaValidationRequired(true);
    }
    // Handle recover with Email option.
    if (pathUrl.equals(RECOVER_PASSWORD_URL)) {
        return preValidationResponse;
    }
    // Handle recover with security questions option.
    HttpServletRequest httpServletRequestWrapper;
    try {
        httpServletRequestWrapper = new CaptchaHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        preValidationResponse.setWrappedHttpServletRequest(httpServletRequestWrapper);
    } catch (IOException e) {
        log.error("Error occurred while wrapping ServletRequest.", e);
        return preValidationResponse;
    }
    String path = httpServletRequestWrapper.getRequestURI();
    User user = new User();
    boolean initializationFlow = false;
    if (CaptchaUtil.isPathAvailable(path, ACCOUNT_SECURITY_QUESTION_URL) || CaptchaUtil.isPathAvailable(path, ACCOUNT_SECURITY_QUESTIONS_URL)) {
        user.setUserName(servletRequest.getParameter("username"));
        if (StringUtils.isNotBlank(servletRequest.getParameter("realm"))) {
            user.setUserStoreDomain(servletRequest.getParameter("realm"));
        } else {
            user.setUserStoreDomain(IdentityUtil.getPrimaryDomainName());
        }
        user.setTenantDomain(servletRequest.getParameter("tenant-domain"));
        initializationFlow = true;
    } else {
        JsonObject requestObject;
        try {
            try (InputStream in = httpServletRequestWrapper.getInputStream()) {
                requestObject = new JsonParser().parse(IOUtils.toString(in)).getAsJsonObject();
            }
        } catch (IOException e) {
            return preValidationResponse;
        }
        UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
        try {
            UserRecoveryData userRecoveryData = userRecoveryDataStore.load(requestObject.get("key").getAsString());
            if (userRecoveryData != null) {
                user = userRecoveryData.getUser();
            }
        } catch (IdentityRecoveryException e) {
            return preValidationResponse;
        }
    }
    if (StringUtils.isBlank(user.getUserName())) {
        // Invalid Request
        return preValidationResponse;
    }
    if (StringUtils.isBlank(user.getTenantDomain())) {
        user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }
    Property[] connectorConfigs;
    try {
        connectorConfigs = identityGovernanceService.getConfiguration(new String[] { RECOVERY_QUESTION_PASSWORD_RECAPTCHA_ENABLE, RECOVERY_QUESTION_PASSWORD_RECAPTCHA_MAX_FAILED_ATTEMPTS }, user.getTenantDomain());
    } catch (IdentityGovernanceException e) {
        throw new CaptchaServerException("Unable to retrieve connector configs.", e);
    }
    String connectorEnabled = null;
    String maxAttemptsStr = null;
    for (Property connectorConfig : connectorConfigs) {
        if ((RECOVERY_QUESTION_PASSWORD_RECAPTCHA_ENABLE).equals(connectorConfig.getName())) {
            connectorEnabled = connectorConfig.getValue();
        } else if ((RECOVERY_QUESTION_PASSWORD_RECAPTCHA_MAX_FAILED_ATTEMPTS).equals(connectorConfig.getName())) {
            maxAttemptsStr = connectorConfig.getValue();
        }
    }
    if (!Boolean.parseBoolean(connectorEnabled)) {
        return preValidationResponse;
    }
    if (StringUtils.isBlank(maxAttemptsStr) || !NumberUtils.isNumber(maxAttemptsStr)) {
        log.warn("Invalid configuration found in the PasswordRecoveryReCaptchaConnector for the tenant - " + user.getTenantDomain());
        return preValidationResponse;
    }
    int maxFailedAttempts = Integer.parseInt(maxAttemptsStr);
    int tenantId;
    try {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } catch (Exception e) {
        // Invalid tenant
        return preValidationResponse;
    }
    try {
        if (CaptchaDataHolder.getInstance().getAccountLockService().isAccountLocked(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain())) {
            return preValidationResponse;
        }
    } catch (AccountLockServiceException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while validating if account is locked for user: " + user.getUserName() + " of user " + "store domain: " + user.getUserStoreDomain() + " and tenant domain: " + user.getTenantDomain());
        }
        return preValidationResponse;
    }
    Map<String, String> claimValues = CaptchaUtil.getClaimValues(user, tenantId, new String[] { FAIL_ATTEMPTS_CLAIM });
    if (claimValues == null || claimValues.isEmpty()) {
        // Invalid user
        return preValidationResponse;
    }
    int currentFailedAttempts = 0;
    if (NumberUtils.isNumber(claimValues.get(FAIL_ATTEMPTS_CLAIM))) {
        currentFailedAttempts = Integer.parseInt(claimValues.get(FAIL_ATTEMPTS_CLAIM));
    }
    HttpServletResponse httpServletResponse = ((HttpServletResponse) servletResponse);
    if (currentFailedAttempts > maxFailedAttempts) {
        if (initializationFlow) {
            httpServletResponse.setHeader("reCaptcha", "true");
            httpServletResponse.setHeader("reCaptchaKey", CaptchaDataHolder.getInstance().getReCaptchaSiteKey());
            httpServletResponse.setHeader("reCaptchaAPI", CaptchaDataHolder.getInstance().getReCaptchaAPIUrl());
        } else {
            preValidationResponse.setCaptchaValidationRequired(true);
            preValidationResponse.setMaxFailedLimitReached(true);
            addPostValidationData(servletRequest);
        }
    } else if (currentFailedAttempts == maxFailedAttempts && !initializationFlow) {
        addPostValidationData(servletRequest);
    }
    return preValidationResponse;
}
Also used : AccountLockServiceException(org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException) CaptchaHttpServletRequestWrapper(org.wso2.carbon.identity.captcha.util.CaptchaHttpServletRequestWrapper) User(org.wso2.carbon.identity.application.common.model.User) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) HttpServletResponse(javax.servlet.http.HttpServletResponse) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) IOException(java.io.IOException) CaptchaClientException(org.wso2.carbon.identity.captcha.exception.CaptchaClientException) CaptchaException(org.wso2.carbon.identity.captcha.exception.CaptchaException) IOException(java.io.IOException) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) IdentityRecoveryException(org.wso2.carbon.identity.recovery.IdentityRecoveryException) IdentityGovernanceException(org.wso2.carbon.identity.governance.IdentityGovernanceException) AccountLockServiceException(org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException) IdentityGovernanceException(org.wso2.carbon.identity.governance.IdentityGovernanceException) CaptchaPreValidationResponse(org.wso2.carbon.identity.captcha.connector.CaptchaPreValidationResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserRecoveryData(org.wso2.carbon.identity.recovery.model.UserRecoveryData) UserRecoveryDataStore(org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore) IdentityRecoveryException(org.wso2.carbon.identity.recovery.IdentityRecoveryException) Property(org.wso2.carbon.identity.application.common.model.Property) JsonParser(com.google.gson.JsonParser)

Example 4 with CaptchaServerException

use of org.wso2.carbon.identity.captcha.exception.CaptchaServerException in project identity-governance by wso2-extensions.

the class CaptchaUtil method isMaximumFailedLoginAttemptsReached.

public static boolean isMaximumFailedLoginAttemptsReached(String usernameWithDomain, String tenantDomain) throws CaptchaException {
    String CONNECTOR_NAME = "sso.login.recaptcha";
    String RECAPTCHA_VERIFICATION_CLAIM = "http://wso2.org/claims/identity/failedLoginAttempts";
    Property[] connectorConfigs;
    try {
        connectorConfigs = CaptchaDataHolder.getInstance().getIdentityGovernanceService().getConfiguration(new String[] { CONNECTOR_NAME + ReCaptchaConnectorPropertySuffixes.ENABLE, CONNECTOR_NAME + ReCaptchaConnectorPropertySuffixes.MAX_ATTEMPTS }, tenantDomain);
    } catch (Exception e) {
        // Can happen due to invalid user/ invalid tenant/ invalid configuration
        if (log.isDebugEnabled()) {
            log.debug("Unable to load connector configuration.", e);
        }
        return false;
    }
    if (connectorConfigs == null) {
        return false;
    }
    String maxAttemptsStr = null;
    for (Property property : connectorConfigs) {
        if ((CONNECTOR_NAME + ReCaptchaConnectorPropertySuffixes.ENABLE).equals(property.getName()) && !Boolean.valueOf(property.getValue())) {
            return false;
        } else if ((CONNECTOR_NAME + ReCaptchaConnectorPropertySuffixes.MAX_ATTEMPTS).equals(property.getName())) {
            maxAttemptsStr = property.getValue();
        }
    }
    if (StringUtils.isBlank(maxAttemptsStr) || !NumberUtils.isNumber(maxAttemptsStr)) {
        throw new CaptchaServerException("Invalid reCaptcha configuration.");
    }
    int maxAttempts = Integer.parseInt(maxAttemptsStr);
    RealmService realmService = CaptchaDataHolder.getInstance().getRealmService();
    int tenantId;
    try {
        tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        // Tenant is already validated in the canHandle section.
        throw new CaptchaServerException("Failed to retrieve tenant id from tenant domain : " + tenantDomain, e);
    }
    if (MultitenantConstants.INVALID_TENANT_ID == tenantId) {
        throw new CaptchaServerException("Invalid tenant domain : " + tenantDomain);
    }
    UserRealm userRealm;
    try {
        userRealm = (UserRealm) realmService.getTenantUserRealm(tenantId);
    } catch (UserStoreException e) {
        throw new CaptchaServerException("Failed to retrieve user realm from tenant id : " + tenantId, e);
    }
    UserStoreManager userStoreManager;
    try {
        userStoreManager = userRealm.getUserStoreManager();
    } catch (UserStoreException e) {
        throw new CaptchaServerException("Failed to retrieve user store manager.", e);
    }
    Map<String, String> claimValues;
    try {
        claimValues = userStoreManager.getUserClaimValues(MultitenantUtils.getTenantAwareUsername(usernameWithDomain), new String[] { RECAPTCHA_VERIFICATION_CLAIM }, UserCoreConstants.DEFAULT_PROFILE);
    } catch (org.wso2.carbon.user.core.UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while retrieving user claims.", e);
        }
        // Invalid user
        return false;
    }
    int currentAttempts = 0;
    if (NumberUtils.isNumber(claimValues.get(RECAPTCHA_VERIFICATION_CLAIM))) {
        currentAttempts = Integer.parseInt(claimValues.get(RECAPTCHA_VERIFICATION_CLAIM));
    }
    return currentAttempts >= maxAttempts;
}
Also used : CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) URISyntaxException(java.net.URISyntaxException) CaptchaClientException(org.wso2.carbon.identity.captcha.exception.CaptchaClientException) CaptchaException(org.wso2.carbon.identity.captcha.exception.CaptchaException) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) IdentityGovernanceException(org.wso2.carbon.identity.governance.IdentityGovernanceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) IOException(java.io.IOException) UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Property(org.wso2.carbon.identity.application.common.model.Property)

Aggregations

CaptchaServerException (org.wso2.carbon.identity.captcha.exception.CaptchaServerException)4 IOException (java.io.IOException)3 CaptchaClientException (org.wso2.carbon.identity.captcha.exception.CaptchaClientException)3 JsonObject (com.google.gson.JsonObject)2 JsonParser (com.google.gson.JsonParser)2 InputStream (java.io.InputStream)2 Property (org.wso2.carbon.identity.application.common.model.Property)2 CaptchaException (org.wso2.carbon.identity.captcha.exception.CaptchaException)2 IdentityGovernanceException (org.wso2.carbon.identity.governance.IdentityGovernanceException)2 UserStoreException (org.wso2.carbon.user.api.UserStoreException)2 UserRealm (org.wso2.carbon.user.core.UserRealm)2 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)2 RealmService (org.wso2.carbon.user.core.service.RealmService)2 URISyntaxException (java.net.URISyntaxException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpEntity (org.apache.http.HttpEntity)1 HttpResponse (org.apache.http.HttpResponse)1 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)1 HttpPost (org.apache.http.client.methods.HttpPost)1