Search in sources :

Example 96 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method redirectToAccountCreateUI.

/**
 * Call the relevant URL to add the new user.
 *
 * @param externalIdPConfig Relevant external IDP.
 * @param context           Authentication context.
 * @param localClaimValues  Local claim values.
 * @param response          HttpServlet response.
 * @param username          Relevant user name
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private void redirectToAccountCreateUI(ExternalIdPConfig externalIdPConfig, AuthenticationContext context, Map<String, String> localClaimValues, HttpServletResponse response, String username, HttpServletRequest request) throws PostAuthenticationFailedException {
    try {
        ServiceURLBuilder uriBuilder = ServiceURLBuilder.create();
        if (externalIdPConfig.isModifyUserNameAllowed()) {
            context.setProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED, true);
            uriBuilder = uriBuilder.addPath(FrameworkUtils.getUserNameProvisioningUIUrl());
            uriBuilder.addParameter(FrameworkConstants.ALLOW_CHANGE_USER_NAME, String.valueOf(true));
            if (log.isDebugEnabled()) {
                log.debug(externalIdPConfig.getName() + " allow to change the username, redirecting to " + "registration endpoint to provision the user: " + username);
            }
        } else {
            uriBuilder = uriBuilder.addPath(FrameworkUtils.getPasswordProvisioningUIUrl());
            if (log.isDebugEnabled()) {
                if (externalIdPConfig.isPasswordProvisioningEnabled()) {
                    log.debug(externalIdPConfig.getName() + " supports password provisioning, redirecting to " + "sign up endpoint to provision the user : " + username);
                }
            }
        }
        if (externalIdPConfig.isPasswordProvisioningEnabled()) {
            uriBuilder.addParameter(FrameworkConstants.PASSWORD_PROVISION_ENABLED, String.valueOf(true));
        }
        if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
            uriBuilder.addParameter(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME, context.getTenantDomain());
        }
        uriBuilder.addParameter(FrameworkConstants.SERVICE_PROVIDER, context.getSequenceConfig().getApplicationConfig().getApplicationName());
        uriBuilder.addParameter(FrameworkConstants.USERNAME, username);
        uriBuilder.addParameter(FrameworkConstants.SKIP_SIGN_UP_ENABLE_CHECK, String.valueOf(true));
        uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());
        addMissingClaims(uriBuilder, context);
        localClaimValues.forEach(uriBuilder::addParameter);
        response.sendRedirect(uriBuilder.build().getRelativePublicURL());
    } catch (IOException | URLBuilderException e) {
        handleExceptions(String.format(ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING.getMessage(), username, externalIdPConfig.getName()), ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING.getCode(), e);
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) IOException(java.io.IOException) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder)

Example 97 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-identity-framework by wso2.

the class PostAuthenticatedSubjectIdentifierHandler method handle.

@Override
public PostAuthnHandlerFlowStatus handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) {
    if (!FrameworkUtils.isStepBasedSequenceHandlerExecuted(context)) {
        return SUCCESS_COMPLETED;
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    String subjectClaimURI = sequenceConfig.getApplicationConfig().getSubjectClaimUri();
    String subjectValue = (String) context.getProperty(FrameworkConstants.SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE);
    try {
        if (StringUtils.isNotBlank(subjectClaimURI)) {
            if (subjectValue != null) {
                handleUserStoreAndTenantDomain(sequenceConfig, subjectValue);
            } else {
                log.warn("Subject claim could not be found. Defaulting to Name Identifier.");
                setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
            }
        } else {
            setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
        }
    } catch (UserIdNotFoundException e) {
        return UNSUCCESS_COMPLETED;
    }
    return SUCCESS_COMPLETED;
}
Also used : SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 98 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-identity-framework by wso2.

the class PostAuthnMissingClaimHandler method handlePostAuthenticationForMissingClaimsResponse.

protected void handlePostAuthenticationForMissingClaimsResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
    if (log.isDebugEnabled()) {
        log.debug("Starting to process the response with missing claims");
    }
    Map<String, String> claims = new HashMap<String, String>();
    Map<String, String> claimsForContext = new HashMap<String, String>();
    Map<String, String[]> requestParams = request.getParameterMap();
    boolean persistClaims = false;
    AuthenticatedUser user = context.getSequenceConfig().getAuthenticatedUser();
    Map<String, String> carbonToSPClaimMapping = new HashMap<>();
    Object spToCarbonClaimMappingObject = context.getProperty(FrameworkConstants.SP_TO_CARBON_CLAIM_MAPPING);
    if (spToCarbonClaimMappingObject instanceof Map) {
        Map<String, String> spToCarbonClaimMapping = (Map<String, String>) spToCarbonClaimMappingObject;
        for (Map.Entry<String, String> entry : spToCarbonClaimMapping.entrySet()) {
            carbonToSPClaimMapping.put(entry.getValue(), entry.getKey());
        }
    }
    boolean doMandatoryClaimsExist = false;
    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
            doMandatoryClaimsExist = true;
            break;
        }
    }
    if (!doMandatoryClaimsExist) {
        // Check whether mandatory claims exist in the request. If not throw error.
        throw new PostAuthenticationFailedException("Mandatory missing claims are not found", "Mandatory missing " + "claims are not found in the request for the session with context identifier: " + context.getContextIdentifier());
    }
    List<String> missingClaims = new ArrayList<>();
    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
            String localClaimURI = entry.getKey().substring(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX.length());
            if (StringUtils.isBlank(entry.getValue()[0])) {
                missingClaims.add(localClaimURI);
                continue;
            }
            claims.put(localClaimURI, entry.getValue()[0]);
            if (spToCarbonClaimMappingObject != null) {
                String spClaimURI = carbonToSPClaimMapping.get(localClaimURI);
                claimsForContext.put(spClaimURI, entry.getValue()[0]);
            } else {
                claimsForContext.put(localClaimURI, entry.getValue()[0]);
            }
        }
    }
    if (CollectionUtils.isNotEmpty(missingClaims)) {
        String missingClaimURIs = StringUtils.join(missingClaims, ",");
        if (log.isDebugEnabled()) {
            log.debug("Claim values for the mandatory claims: " + missingClaimURIs + " are empty");
        }
        throw new PostAuthenticationFailedException("Mandatory claim is not found", "Claim " + "values for the claim URIs: " + missingClaimURIs + " are empty");
    }
    Map<ClaimMapping, String> authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(claimsForContext);
    authenticatedUserAttributes.putAll(user.getUserAttributes());
    for (Map.Entry<Integer, StepConfig> entry : context.getSequenceConfig().getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        if (stepConfig.isSubjectAttributeStep()) {
            if (stepConfig.getAuthenticatedUser() != null) {
                user = stepConfig.getAuthenticatedUser();
            }
            if (!user.isFederatedUser()) {
                persistClaims = true;
            } else {
                String associatedID;
                String subject = user.getAuthenticatedSubjectIdentifier();
                try {
                    FederatedAssociationManager federatedAssociationManager = FrameworkUtils.getFederatedAssociationManager();
                    associatedID = federatedAssociationManager.getUserForFederatedAssociation(context.getTenantDomain(), stepConfig.getAuthenticatedIdP(), subject);
                    if (StringUtils.isNotBlank(associatedID)) {
                        String fullQualifiedAssociatedUserId = FrameworkUtils.prependUserStoreDomainToName(associatedID + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
                        UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedID));
                        user = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(fullQualifiedAssociatedUserId);
                        persistClaims = true;
                    }
                } catch (FederatedAssociationManagerException | FrameworkException e) {
                    throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while getting association for " + subject, e);
                }
            }
            break;
        }
    }
    if (persistClaims) {
        if (log.isDebugEnabled()) {
            log.debug("Local user mapping found. Claims will be persisted");
        }
        try {
            Map<String, String> claimMapping = context.getSequenceConfig().getApplicationConfig().getClaimMappings();
            Map<String, String> localIdpClaims = new HashMap<>();
            for (Map.Entry<String, String> entry : claims.entrySet()) {
                String localClaim = claimMapping.get(entry.getKey());
                localIdpClaims.put(localClaim, entry.getValue());
            }
            if (log.isDebugEnabled()) {
                log.debug("Updating user profile of user : " + user.getLoggableUserId());
            }
            UserRealm realm = getUserRealm(user.getTenantDomain());
            AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) realm.getUserStoreManager();
            userStoreManager.setUserClaimValuesWithID(user.getUserId(), localIdpClaims, null);
        } catch (UserStoreException e) {
            if (e instanceof UserStoreClientException) {
                context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR, e.getMessage());
                if (StringUtils.isNotBlank(e.getErrorCode())) {
                    context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE, e.getErrorCode());
                }
                /*
                    When the attribute update is disabled for JIT provisioned users, the mandatory claim update
                    request will be identified through the error code and handled it.
                     */
                if (ERROR_CODE_INVALID_ATTRIBUTE_UPDATE.equals(e.getErrorCode())) {
                    context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
                    return;
                }
            }
            if (ErrorMessages.ERROR_CODE_READONLY_USER_STORE.getCode().equals(e.getErrorCode())) {
                context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
                return;
            }
            throw new PostAuthenticationFailedException(e.getMessage(), "Error while updating claims for local user. Could not update profile", e);
        } catch (UserIdNotFoundException e) {
            throw new PostAuthenticationFailedException("User id not found", "User id not found for local user. Could not update profile", e);
        }
    }
    context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
}
Also used : HashMap(java.util.HashMap) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) ArrayList(java.util.ArrayList) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) FederatedAssociationManager(org.wso2.carbon.identity.user.profile.mgt.association.federation.FederatedAssociationManager) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) FederatedAssociationManagerException(org.wso2.carbon.identity.user.profile.mgt.association.federation.exception.FederatedAssociationManagerException) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) Map(java.util.Map) HashMap(java.util.HashMap)

Example 99 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-identity-framework by wso2.

the class PostAuthnMissingClaimHandler method handlePostAuthenticationForMissingClaimsRequest.

protected PostAuthnHandlerFlowStatus handlePostAuthenticationForMissingClaimsRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
    String[] missingClaims = FrameworkUtils.getMissingClaims(context);
    if (StringUtils.isNotBlank(missingClaims[0])) {
        if (log.isDebugEnabled()) {
            log.debug("Mandatory claims missing for the application : " + missingClaims[0]);
        }
        try {
            // If there are read only claims marked as mandatory and they are missing, we cannot proceed further.
            // We have to end the flow and show an error message to user.
            ClaimManager claimManager = getUserRealm(context.getTenantDomain()).getClaimManager();
            Map<String, String> missingClaimMap = FrameworkUtils.getMissingClaimsMap(context);
            for (Map.Entry<String, String> missingClaim : missingClaimMap.entrySet()) {
                Claim claimObj = claimManager.getClaim(missingClaim.getValue());
                if (claimObj != null && claimObj.isReadOnly()) {
                    throw new PostAuthenticationFailedException("One or more read-only claim is missing in the " + "requested claim set. Please contact your administrator for more information about " + "this issue.", "One or more read-only claim is missing in the requested claim set");
                }
            }
            List<LocalClaim> localClaims = getClaimMetadataManagementService().getLocalClaims(context.getTenantDomain());
            String displayNames = getMissingClaimsDisplayNames(missingClaimMap, localClaims);
            URIBuilder uriBuilder = new URIBuilder(ConfigurationFacade.getInstance().getAuthenticationEndpointMissingClaimsURL());
            uriBuilder.addParameter(FrameworkConstants.MISSING_CLAIMS, missingClaims[0]);
            uriBuilder.addParameter(FrameworkConstants.DISPLAY_NAMES, displayNames);
            uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());
            uriBuilder.addParameter(FrameworkConstants.REQUEST_PARAM_SP, context.getSequenceConfig().getApplicationConfig().getApplicationName());
            if (context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR) != null) {
                uriBuilder.addParameter("errorMessage", context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR).toString());
                context.removeProperty(POST_AUTH_MISSING_CLAIMS_ERROR);
            }
            if (context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE) != null) {
                uriBuilder.addParameter("errorCode", context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE).toString());
                context.removeProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE);
            }
            response.sendRedirect(uriBuilder.build().toString());
            context.setProperty(POST_AUTHENTICATION_REDIRECTION_TRIGGERED, true);
            if (log.isDebugEnabled()) {
                log.debug("Redirecting to outside to pick mandatory claims");
            }
        } catch (IOException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error " + "while redirecting to request claims page", e);
        } catch (URISyntaxException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while building redirect URI", e);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while retrieving claim from claim URI.", e);
        } catch (ClaimMetadataException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while retrieving claim metadata.", e);
        }
        return PostAuthnHandlerFlowStatus.INCOMPLETE;
    } else {
        return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED;
    }
}
Also used : ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) LocalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder) ClaimManager(org.wso2.carbon.user.api.ClaimManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) Map(java.util.Map) HashMap(java.util.HashMap) LocalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim) Claim(org.wso2.carbon.user.api.Claim)

Example 100 with Claim

use of org.wso2.carbon.identity.application.common.model.xsd.Claim in project carbon-identity-framework by wso2.

the class ConsentMgtPostAuthnHandler method getSPRequestedLocalClaims.

private List<String> getSPRequestedLocalClaims(AuthenticationContext context) throws PostAuthenticationFailedException {
    List<String> spRequestedLocalClaims = new ArrayList<>();
    ApplicationConfig applicationConfig = context.getSequenceConfig().getApplicationConfig();
    if (applicationConfig == null) {
        ServiceProvider serviceProvider = getServiceProvider(context);
        String error = "Application configs are null in AuthenticationContext for SP: " + serviceProvider.getApplicationName() + " in tenant domain: " + getSPTenantDomain(serviceProvider);
        throw new PostAuthenticationFailedException("Authentication failed. Error while processing application " + "claim configurations.", error);
    }
    Map<String, String> claimMappings = applicationConfig.getRequestedClaimMappings();
    if (isNotEmpty(claimMappings) && isNotEmpty(claimMappings.values())) {
        spRequestedLocalClaims = new ArrayList<>(claimMappings.values());
    }
    String subjectClaimUri = getSubjectClaimUri(applicationConfig);
    spRequestedLocalClaims.remove(subjectClaimUri);
    if (isDebugEnabled()) {
        String message = String.format("Requested claims for SP: %s - " + spRequestedLocalClaims, applicationConfig.getApplicationName());
        logDebug(message);
    }
    return spRequestedLocalClaims;
}
Also used : ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ArrayList(java.util.ArrayList) StringUtils.defaultString(org.apache.commons.lang.StringUtils.defaultString) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)

Aggregations

HashMap (java.util.HashMap)112 ArrayList (java.util.ArrayList)89 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)66 UserStoreException (org.wso2.carbon.user.api.UserStoreException)65 Test (org.testng.annotations.Test)63 ClaimMetadataException (org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException)55 Map (java.util.Map)49 PreparedStatement (java.sql.PreparedStatement)48 SQLException (java.sql.SQLException)43 LocalClaim (org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim)34 RealmService (org.wso2.carbon.user.core.service.RealmService)30 UserRealm (org.wso2.carbon.user.core.UserRealm)29 Claim (org.wso2.carbon.user.api.Claim)28 UserStoreException (org.wso2.carbon.user.core.UserStoreException)28 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)28 ResultSet (java.sql.ResultSet)27 Connection (java.sql.Connection)25 ClaimConfig (org.wso2.carbon.identity.application.common.model.ClaimConfig)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)24 Claim (org.wso2.carbon.identity.application.common.model.Claim)24