org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants Java Examples

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsAuthenticatedUser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasMember(String name) {

    switch (name) {
        case FrameworkConstants.JSAttributes.JS_AUTHENTICATED_SUBJECT_IDENTIFIER:
            return getWrapped().getAuthenticatedSubjectIdentifier() != null;
        case FrameworkConstants.JSAttributes.JS_USERNAME:
            return getWrapped().getUserName() != null;
        case FrameworkConstants.JSAttributes.JS_USER_STORE_DOMAIN:
            return getWrapped().getUserStoreDomain() != null;
        case FrameworkConstants.JSAttributes.JS_TENANT_DOMAIN:
            return getWrapped().getTenantDomain() != null;
        case FrameworkConstants.JSAttributes.JS_LOCAL_CLAIMS:
            return idp != null;
        case FrameworkConstants.JSAttributes.JS_REMOTE_CLAIMS:
            return idp != null && !FrameworkConstants.LOCAL.equals(idp);
        default:
            return super.hasMember(name);
    }
}
 
Example #2
Source File: DefaultSequenceHandlerUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Used to get the service provider mapped local role claim URI.
 *
 * @param appConfig ApplicationConfig.
 * @return Service Provider mapped role claim URI.
 */
private static String getSPMappedLocalRoleClaimURI(ApplicationConfig appConfig) {

    String spRoleClaimUri = appConfig.getRoleClaim();
    if (StringUtils.isNotBlank(spRoleClaimUri)) {

        Map<String, String> spToLocalClaimMapping = appConfig.getClaimMappings();
        if (MapUtils.isNotEmpty(spToLocalClaimMapping)) {

            for (Map.Entry<String, String> entry : spToLocalClaimMapping.entrySet()) {
                if (spRoleClaimUri.equals(entry.getKey())) {
                    return entry.getValue();
                }
            }
        }
    }
    return FrameworkConstants.LOCAL_ROLE_CLAIM_URI;
}
 
Example #3
Source File: JsAuthenticatedUser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String[] getLocalRoles() {

        if (idp == null || FrameworkConstants.LOCAL.equals(idp)) {
            RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
            int usersTenantId = IdentityTenantUtil.getTenantId(getWrapped().getTenantDomain());

            try {
                String usernameWithDomain = UserCoreUtil.addDomainToName(getWrapped().getUserName(), getWrapped()
                    .getUserStoreDomain());
                UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
                return userRealm.getUserStoreManager().getRoleListOfUser(usernameWithDomain);
            } catch (UserStoreException e) {
                LOG.error("Error when getting role list of user: " + getWrapped(), e);
            }
        }
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
 
Example #4
Source File: JsAuthenticatedUser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void setMember(String name, Object value) {

    switch (name) {
        case FrameworkConstants.JSAttributes.JS_USERNAME:
            getWrapped().setUserName((String) value);
            break;
        case FrameworkConstants.JSAttributes.JS_USER_STORE_DOMAIN:
            getWrapped().setUserStoreDomain((String) value);
            break;
        case FrameworkConstants.JSAttributes.JS_TENANT_DOMAIN:
            getWrapped().setTenantDomain((String) value);
            break;
        default:
            super.setMember(name, value);
    }
}
 
Example #5
Source File: FileBasedConfigurationBuilder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void readAuthenticatorConfigs(OMElement documentElement) {
    OMElement authenticatorConfigsElem = documentElement.getFirstChildWithName(IdentityApplicationManagementUtil.
            getQNameWithIdentityApplicationNS(FrameworkConstants.Config.QNAME_AUTHENTICATOR_CONFIGS));

    if (authenticatorConfigsElem != null) {
        // for each and every authenticator defined, create an AuthenticatorConfig instance
        for (Iterator authenticatorConfigElements = authenticatorConfigsElem.getChildrenWithLocalName(FrameworkConstants.Config.ELEM_AUTHENTICATOR_CONFIG);
             authenticatorConfigElements.hasNext(); ) {
            AuthenticatorConfig authenticatorConfig = processAuthenticatorConfigElement((OMElement) authenticatorConfigElements.next());

            if (authenticatorConfig != null) {
                this.authenticatorConfigMap.put(authenticatorConfig.getName(), authenticatorConfig);
            }
        }
    }
}
 
Example #6
Source File: FileBasedConfigurationBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void readMaximumLoginAttemptCount(OMElement documentElement) {
    OMElement maxLoginAttemptCountElem = documentElement.getFirstChildWithName(IdentityApplicationManagementUtil.
            getQNameWithIdentityApplicationNS(FrameworkConstants.Config.QNAME_MAX_LOGIN_ATTEMPT_COUNT));

    if (maxLoginAttemptCountElem != null) {
        String maxLoginAttemptCountStr = maxLoginAttemptCountElem.getText();

        if (maxLoginAttemptCountStr != null && !maxLoginAttemptCountStr.isEmpty()) {
            try {
                maxLoginAttemptCount = Integer.parseInt(maxLoginAttemptCountElem.getText());
            } catch (NumberFormatException e) {
                log.error("MaxLoginAttemptCount must be a number");
                maxLoginAttemptCount = 5;
            }
        }
    }
}
 
Example #7
Source File: GraphBasedSequenceHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void gotoToNextNode(AuthenticationContext context, SequenceConfig sequenceConfig,
                            AuthGraphNode currentNode) {

    AuthGraphNode nextNode = null;
    if (currentNode instanceof StepConfigGraphNode) {
        nextNode = ((StepConfigGraphNode) currentNode).getNext();
    }
    if (nextNode == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Next node found for the current graph node : " + currentNode.getName() +
                    ", Service Provider: " + context.getServiceProviderName() +
                    " . Ending the authentication flow.");
        }
        nextNode = new EndStep();
    }

    context.setProperty(FrameworkConstants.JSAttributes.PROP_CURRENT_NODE, nextNode);
}
 
Example #8
Source File: DefaultStepBasedSequenceHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "spClaimMappingProvider")
public Object[][] getSpClaimMappingProvider() {
    return new Object[][]{
            {       // SP mapped role claim
                    new HashMap<String, String>() {{
                        put("SP_ROLE_CLAIM", FrameworkConstants.LOCAL_ROLE_CLAIM_URI);
                    }},
                    "SP_ROLE_CLAIM"
            },
            {       // Role claim not among SP mapped claims
                    new HashMap<String, String>() {{
                        put("SP_CLAIM", "LOCAL_CLAIM");
                    }},
                    FrameworkConstants.LOCAL_ROLE_CLAIM_URI
            },
            {      // No SP mapped claims
                    new HashMap<>(), FrameworkConstants.LOCAL_ROLE_CLAIM_URI
            },
            {
                    null, FrameworkConstants.LOCAL_ROLE_CLAIM_URI
            }
    };
}
 
Example #9
Source File: JITProvisioningPostAuthenticationHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * To build ReceiptServices from the incoming receipt.
 *
 * @param receipt Relevant incoming receipt send from the client side.
 * @return Set of the receipt services.
 */
private List<ReceiptServiceInput> getReceiptServiceInputs(JSONObject receipt) {

    JSONArray services = receipt.getJSONArray(FrameworkConstants.Consent.SERVICES);
    List<ReceiptServiceInput> receiptServiceInputs = new ArrayList<>();
    for (int serviceIndex = 0; serviceIndex < services.length(); serviceIndex++) {
        JSONObject service = services.getJSONObject(serviceIndex);
        ReceiptServiceInput receiptServiceInput = new ReceiptServiceInput();

        JSONArray purposes = service.getJSONArray(FrameworkConstants.Consent.PURPOSES);
        List<ReceiptPurposeInput> receiptPurposeInputs = new ArrayList<>();
        for (int purposeIndex = 0; purposeIndex < purposes.length(); purposeIndex++) {
            receiptPurposeInputs.add(getReceiptPurposeInputs((JSONObject) purposes.get(purposeIndex)));
        }
        receiptServiceInput.setPurposes(receiptPurposeInputs);
        receiptServiceInputs.add(receiptServiceInput);
    }
    return receiptServiceInputs;
}
 
Example #10
Source File: AbstractApplicationAuthenticator.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get map of runtime params set through the script.
 *
 * @param context context
 * @return Map of params
 */
public Map<String, String> getRuntimeParams(AuthenticationContext context) {

    Map<String, String> runtimeParams = context.getAuthenticatorParams(getName());
    Map<String, String> commonParams = context
            .getAuthenticatorParams(FrameworkConstants.JSAttributes.JS_COMMON_OPTIONS);
    if (MapUtils.isNotEmpty(commonParams)) {
        if (runtimeParams != null) {
            commonParams.putAll(runtimeParams);
        }
        return commonParams;
    } else if (runtimeParams != null) {
        return runtimeParams;
    }
    return Collections.emptyMap();
}
 
Example #11
Source File: PostAuthenticationMgtService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void setPASTRCookie(AuthenticationContext context, HttpServletRequest request,
        HttpServletResponse response) {

    if (context.getParameter(FrameworkConstants.PASTR_COOKIE) != null) {
        if (log.isDebugEnabled()) {
            log.debug("PASTR cookie is already set to context : " + context.getContextIdentifier());
        }
        return;
    } else {
        if (log.isDebugEnabled()) {
            log.debug(
                    "PASTR cookie is not set to context : " + context.getContextIdentifier() + ". Hence setting the"
                            + " " + "cookie");
        }
        String pastrCookieValue = UUIDGenerator.generateUUID();
        FrameworkUtils
                .setCookie(request, response, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()),
                        pastrCookieValue, -1);
        context.addParameter(FrameworkConstants.PASTR_COOKIE, pastrCookieValue);
    }
}
 
Example #12
Source File: JsGraphBuilderFactory.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public ScriptEngine createEngine(AuthenticationContext authenticationContext) {

        ScriptEngine engine = factory.getScriptEngine("--no-java");

        Bindings bindings = engine.createBindings();
        engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
        engine.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
        SelectAcrFromFunction selectAcrFromFunction = new SelectAcrFromFunction();
//        todo move to functions registry
        bindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SELECT_ACR_FROM,
            (SelectOneFunction) selectAcrFromFunction::evaluate);

        JsLogger jsLogger = new JsLogger();
        bindings.put(FrameworkConstants.JSAttributes.JS_LOG, jsLogger);
        return engine;
    }
 
Example #13
Source File: AbstractRequestCoordinator.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the sequence config related to current Authentication Context.
 * @param context  Authentication Context
 * @param parameterMap Parameter Map, retrieved from (Http/etc) Request.
 * @return Generated Sequence Config.
 * @throws FrameworkException when there is an error in loading the Sequence Config, most probably error
 * in underlying data persistence layer.
 */
public SequenceConfig getSequenceConfig(AuthenticationContext context, Map<String, String[]> parameterMap)
        throws FrameworkException {
    String requestType = context.getRequestType();
    String[] issuers = parameterMap.get(FrameworkConstants.RequestParams.ISSUER);
    String issuer = null;
    if (!ArrayUtils.isEmpty(issuers)) {
        issuer = issuers[0];
    }
    String tenantDomain = context.getTenantDomain();

    SequenceLoader sequenceBuilder = FrameworkServiceDataHolder.getInstance().getSequenceLoader();
    if (sequenceBuilder != null) {
        ServiceProvider serviceProvider = getServiceProvider(requestType, issuer, tenantDomain);
        return sequenceBuilder.getSequenceConfig(context, parameterMap, serviceProvider);
    } else {
        //Backward compatibility, Using the deprecated method.
        //TODO: Need to remove the dependency to this.
        return ConfigurationFacade.getInstance().getSequenceConfig(issuer, requestType, tenantDomain);
    }

}
 
Example #14
Source File: AuthenticationContext.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Add authentication params to the message context parameters Map.
 *
 * @param authenticatorParams Map of authenticator and params.
 */
public void addAuthenticatorParams(Map<String, Map<String, String>> authenticatorParams) {

    if (MapUtils.isEmpty(authenticatorParams)) {
        return;
    }
    Object runtimeParamsObj = getParameter(FrameworkConstants.RUNTIME_PARAMS);
    if (runtimeParamsObj == null) {
        addParameter(FrameworkConstants.RUNTIME_PARAMS, authenticatorParams);
        return;
    }
    if (runtimeParamsObj instanceof Map) {
        Map<String, Map<String, String>> runtimeParams = (Map<String, Map<String, String>>) runtimeParamsObj;
        for (Map.Entry<String, Map<String, String>> params : authenticatorParams.entrySet()) {
            if (runtimeParams.get(params.getKey()) != null) {
                runtimeParams.get(params.getKey()).putAll(params.getValue());
            } else {
                runtimeParams.put(params.getKey(), params.getValue());
            }
        }
    } else {
        throw IdentityRuntimeException.error("There is already a object set with RUNTIME_PARAMS key in the " +
                "message context.");
    }
}
 
Example #15
Source File: PostAuthenticatedSubjectIdentifierHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@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);
    if (StringUtils.isNotBlank(subjectClaimURI)) {
        if (subjectValue != null) {
            handleUserStoreAndTenantDomain(sequenceConfig, subjectValue);
        } else {
            log.warn("Subject claim could not be found. Defaulting to Name Identifier.");
            setAuthenticatedSujectIdentifierBasedOnUserName(sequenceConfig);
        }
    } else {
        setAuthenticatedSujectIdentifierBasedOnUserName(sequenceConfig);

    }
    return SUCCESS_COMPLETED;
}
 
Example #16
Source File: FrameworkLogoutResponseFactory.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void create(
        HttpIdentityResponse.HttpIdentityResponseBuilder builder, IdentityResponse identityResponse) {

    FrameworkLogoutResponse response = (FrameworkLogoutResponse)identityResponse;

    builder.setStatusCode(HttpServletResponse.SC_FOUND);
    builder.addParameter(InboundConstants.RequestProcessor.AUTH_NAME,
                         new String[]{response.getAuthName()});
    builder.addParameter(FrameworkConstants.SESSION_DATA_KEY,
                         new String[]{response.getContextKey()});
    builder.addParameter(FrameworkConstants.RequestParams.CALLER_PATH,
                         new String[]{response.getCallbackPath()});
    builder.addParameter(FrameworkConstants.RequestParams.ISSUER,
                         new String[]{response.getRelyingParty()});
    builder.addParameter(FrameworkConstants.RequestParams.TYPE,
                         new String[]{response.getAuthType()});
    builder.setRedirectURL(response.getRedirectUrl());

}
 
Example #17
Source File: DefaultAuthenticationRequestHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private AuthenticationResult getAuthenticationResult(HttpServletRequest request,
                                                     HttpServletResponse response,
                                                     AuthenticationContext context) {

    AuthenticationResult authenticationResult = null;
    if (FrameworkUtils.getCacheDisabledAuthenticators().contains(context.getRequestType())
            && (response instanceof CommonAuthResponseWrapper) &&
            !((CommonAuthResponseWrapper) response).isWrappedByFramework()) {
        // Get the authentication result from the request
        authenticationResult =
                (AuthenticationResult) request.getAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT);
    } else {
        // Retrieve the authentication result from cache
        AuthenticationResultCacheEntry authenticationResultCacheEntry =
                FrameworkUtils.getAuthenticationResultFromCache(context.getCallerSessionKey());
        if (authenticationResultCacheEntry != null) {
            authenticationResult = authenticationResultCacheEntry.getResult();
        }
    }
    return authenticationResult;
}
 
Example #18
Source File: SAMLInboundFunctions.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
public static InboundAuthenticationRequestConfig createSAMLInbound(SAML2Configuration saml2Configuration) {

        SAML2ServiceProvider samlManualConfiguration = saml2Configuration.getManualConfiguration();

        String issuer;
        if (saml2Configuration.getMetadataFile() != null) {
            issuer = createSAMLSpWithMetadataFile(saml2Configuration.getMetadataFile());
        } else if (saml2Configuration.getMetadataURL() != null) {
            issuer = createSAMLSpWithMetadataUrl(saml2Configuration.getMetadataURL());
        } else if (samlManualConfiguration != null) {
            issuer = createSAMLSpWithManualConfiguration(samlManualConfiguration);
        } else {
            throw Utils.buildBadRequestError("Invalid SAML2 Configuration. One of metadataFile, metaDataUrl or " +
                    "serviceProvider manual configuration needs to be present.");
        }

        InboundAuthenticationRequestConfig samlInbound = new InboundAuthenticationRequestConfig();
        samlInbound.setInboundAuthType(FrameworkConstants.StandardInboundProtocols.SAML2);
        samlInbound.setInboundAuthKey(issuer);
        return samlInbound;
    }
 
Example #19
Source File: FileBasedConfigurationBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void readIdpConfigs(OMElement documentElement) {
    OMElement idpConfigsElem = documentElement.getFirstChildWithName(IdentityApplicationManagementUtil.
            getQNameWithIdentityApplicationNS(FrameworkConstants.Config.QNAME_IDP_CONFIGS));

    if (idpConfigsElem != null) {
        // for each and every external idp defined, create an ExternalIdPConfig instance
        for (Iterator idpConfigElements = idpConfigsElem.getChildrenWithLocalName(FrameworkConstants.Config.ELEM_IDP_CONFIG);
             idpConfigElements.hasNext(); ) {

            ExternalIdPConfig idpConfig = processIdPConfigElement((OMElement) idpConfigElements.next());

            if (idpConfig != null) {
                idpList.add(idpConfig);
            }
        }
    }
}
 
Example #20
Source File: FileBasedConfigurationBuilder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void readFilteringEnabledHostNames(OMElement documentElement){
    OMElement filteringEnabledHostNamesElem = documentElement.getFirstChildWithName(IdentityApplicationManagementUtil.
            getQNameWithIdentityApplicationNS(FrameworkConstants.Config.QNAME_FILTERING_ENABLED_HOST_NAMES));
    if (filteringEnabledHostNamesElem != null) {
        Iterator<OMElement> hostNames = filteringEnabledHostNamesElem.getChildrenWithName(IdentityApplicationManagementUtil.
                getQNameWithIdentityApplicationNS(FrameworkConstants.Config.ELEM_HOST_NAME));
        if (hostNames != null) {
            while (hostNames.hasNext()) {
                OMElement hostNameElement = hostNames.next();
                if (hostNameElement != null) {
                    filteringEnabledHostNames.add(hostNameElement.getText());
                }
            }
        }
    }
}
 
Example #21
Source File: AbstractLocalApplicationAuthenticator.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * To decide whether need to redirect the user to login page to retry authentication.
 *
 * @param request  the httpServletRequest
 * @param response the httpServletResponse
 * @param context  the authentication context
 * @param e        the authentication failed exception
 * @return authentication flow status
 * @throws AuthenticationFailedException the exception in the authentication flow
 */
protected AuthenticatorFlowStatus handleRetryOnFailure(HttpServletRequest request,
                                                                HttpServletResponse response,
                                                                AuthenticationContext context,
                                                                AuthenticationFailedException e)
        throws AuthenticationFailedException {

    boolean sendToMultiOptionPage =
            isStepHasMultiOption(context) && isRedirectToMultiOptionPageOnFailure();
    if (retryAuthenticationEnabled(context) && !sendToMultiOptionPage) {
        // The Authenticator will re-initiate the authentication and retry.
        context.setRetrying(true);
        return initiateAuthenticationFlow(request, response, context);
    } else {
        context.setProperty(FrameworkConstants.LAST_FAILED_AUTHENTICATOR, getName());
        /*
            By throwing this exception step handler will redirect to multi options page if
            multi-option are available in the step.
         */
        throw e;
    }
}
 
Example #22
Source File: DefaultStepBasedSequenceHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param externalIdPConfig
 * @return
 */
protected String getIdpRoleClaimUri(ExternalIdPConfig externalIdPConfig)
        throws FrameworkException {
    // get external identity provider role claim uri.
    String idpRoleClaimUri = externalIdPConfig.getRoleClaimUri();

    if (idpRoleClaimUri == null || idpRoleClaimUri.isEmpty()) {
        // no role claim uri defined
        // we can still try to find it out - lets have a look at the claim
        // mapping.
        ClaimMapping[] idpToLocalClaimMapping = externalIdPConfig.getClaimMappings();

        if (idpToLocalClaimMapping != null && idpToLocalClaimMapping.length > 0) {

            for (ClaimMapping mapping : idpToLocalClaimMapping) {
                if (FrameworkConstants.LOCAL_ROLE_CLAIM_URI.equals(
                        mapping.getLocalClaim().getClaimUri()) && mapping.getRemoteClaim() != null) {
                    return mapping.getRemoteClaim().getClaimUri();
                }
            }
        }
    }

    return idpRoleClaimUri;
}
 
Example #23
Source File: JsServletResponse.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasMember(String name) {

    if (getResponse() == null) {
        //Transient Object is null, hence no member access is possible.
        return false;
    }

    switch (name) {
    case FrameworkConstants.JSAttributes.JS_HEADERS:
        return getResponse().getHeaderNames() != null;
    default:
        return super.hasMember(name);
    }
}
 
Example #24
Source File: FileBasedConfigurationBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void readAuthenticationEndpointRedirectParams(OMElement documentElement) {

        OMElement authEndpointRedirectParamsElem = documentElement.getFirstChildWithName(
                IdentityApplicationManagementUtil.getQNameWithIdentityApplicationNS(
                        FrameworkConstants.Config.QNAME_AUTH_ENDPOINT_REDIRECT_PARAMS));

        if (authEndpointRedirectParamsElem != null) {

            authEndpointRedirectParamsConfigAvailable = true;
            OMAttribute actionAttr = authEndpointRedirectParamsElem.getAttribute(new QName(
                    FrameworkConstants.Config.ATTR_AUTH_ENDPOINT_QUERY_PARAM_ACTION));
            OMAttribute removeOnConsumeAttr = authEndpointRedirectParamsElem.getAttribute(new QName(
                    FrameworkConstants.Config.REMOVE_PARAM_ON_CONSUME));
            authEndpointRedirectParamsAction = FrameworkConstants.AUTH_ENDPOINT_QUERY_PARAMS_ACTION_EXCLUDE;

            if (actionAttr != null) {
                String actionValue = actionAttr.getAttributeValue();

                if (actionValue != null && !actionValue.isEmpty()) {
                    authEndpointRedirectParamsAction = actionValue;
                }
            }

            if (removeOnConsumeAttr != null) {
                removeAPIParametersOnConsume = Boolean.parseBoolean(removeOnConsumeAttr.getAttributeValue());
            }

            for (Iterator authEndpointRedirectParamElems = authEndpointRedirectParamsElem
                    .getChildrenWithLocalName(FrameworkConstants.Config.ELEM_AUTH_ENDPOINT_REDIRECT_PARAM);
                 authEndpointRedirectParamElems.hasNext(); ) {
                String redirectParamName = processAuthEndpointQueryParamElem((OMElement) authEndpointRedirectParamElems
                        .next());

                if (redirectParamName != null) {
                    this.authEndpointRedirectParams.add(redirectParamName);
                }
            }
        }
    }
 
Example #25
Source File: DefaultAuthenticationRequestHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Populate any error information sent from Authenticators to be sent in the Response from the authentication
 * framework. By default we retrieve the error information from the AuthenticationContext and populate the error
 * it within the AuthenticationResult as properties.
 *
 * @param request
 * @param response
 * @param context
 */
protected void populateErrorInformation(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationContext context) {

    // get the authentication result
    AuthenticationResult authenticationResult = getAuthenticationResult(request, response, context);

    String errorCode = String.valueOf(context.getProperty(FrameworkConstants.AUTH_ERROR_CODE));
    String errorMessage = String.valueOf(context.getProperty(FrameworkConstants.AUTH_ERROR_MSG));
    String errorUri = String.valueOf(context.getProperty(FrameworkConstants.AUTH_ERROR_URI));

    if (authenticationResult != null) {

        if (IdentityUtil.isNotBlank(errorCode)) {
            // set the custom error code
            authenticationResult.addProperty(FrameworkConstants.AUTH_ERROR_CODE, errorCode);
        }

        if (IdentityUtil.isNotBlank(errorMessage)) {
            // set the custom error message
            authenticationResult.addProperty(FrameworkConstants.AUTH_ERROR_MSG, errorMessage);
        }

        if (IdentityUtil.isNotBlank(errorUri)) {
            // set the custom error uri
            authenticationResult.addProperty(FrameworkConstants.AUTH_ERROR_URI, errorUri);
        }

        if (log.isDebugEnabled()) {
            log.debug("Populated errorCode=" + errorCode + ", errorMessage=" + errorMessage + ", errorUri=" +
                    errorUri + " to the AuthenticationResult.");
        }

        // set the updated authentication result to request
        request.setAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT, authenticationResult);
    }
}
 
Example #26
Source File: JsStep.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private List<Map<String, String>> getOptions() {

        List<Map<String, String>> optionsList = new ArrayList<>();
        Optional<StepConfig> optionalStepConfig = getContext().getSequenceConfig().getStepMap().values().stream()
                .filter(stepConfig -> stepConfig.getOrder() == step).findFirst();
        optionalStepConfig.ifPresent(stepConfig -> stepConfig.getAuthenticatorList().forEach(
                authConfig -> authConfig.getIdpNames().forEach(name -> {
                    Map<String, String> option = new HashMap<>();
                    option.put(FrameworkConstants.JSAttributes.IDP, name);
                    option.put(FrameworkConstants.JSAttributes.AUTHENTICATOR, authConfig.getApplicationAuthenticator()
                            .getName());
                    optionsList.add(option);
                })));
        return optionsList;
    }
 
Example #27
Source File: DefaultRequestPathBasedSequenceHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param appConfig
 * @return
 */
protected String getSpRoleClaimUri(ApplicationConfig appConfig) throws FrameworkException {
    // get external identity provider role claim uri.
    String spRoleClaimUri = appConfig.getRoleClaim();

    if (spRoleClaimUri == null) {
        // no role claim uri defined
        // we can still try to find it out - lets have a look at the claim
        // mapping.
        Map<String, String> spToLocalClaimMapping = appConfig.getClaimMappings();

        if (spToLocalClaimMapping != null && !spToLocalClaimMapping.isEmpty()) {

            for (Entry<String, String> entry : spToLocalClaimMapping.entrySet()) {
                if (FrameworkConstants.LOCAL_ROLE_CLAIM_URI.equals(entry.getValue())) {
                    return entry.getKey();
                }
            }
        }
    }

    if (spRoleClaimUri == null) {
        spRoleClaimUri = FrameworkConstants.LOCAL_ROLE_CLAIM_URI;
        if (log.isDebugEnabled()) {
            String serviceProvider = appConfig.getApplicationName();
            log.debug("Service Provider Role Claim URI not configured for SP: " + serviceProvider +
                    ". Defaulting to " + spRoleClaimUri);
        }
    }

    return spRoleClaimUri;
}
 
Example #28
Source File: FileBasedConfigurationBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private String processAuthEndpointQueryParamElem(OMElement authEndpointQueryParamElem) {

        OMAttribute nameAttr = authEndpointQueryParamElem.getAttribute(new QName(
                FrameworkConstants.Config.ATTR_AUTH_ENDPOINT_QUERY_PARAM_NAME));

        if (nameAttr == null) {
            log.warn("Each Authentication Endpoint Query Param should have a unique name attribute. This Query Param will skipped.");
            return null;
        }

        return nameAttr.getAttributeValue();
    }
 
Example #29
Source File: DefaultStepHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private AuthenticatorConfig getAuthenticatorConfig() {
    AuthenticatorConfig authConfig = FileBasedConfigurationBuilder.getInstance().getAuthenticatorBean
            (FrameworkConstants.BASIC_AUTHENTICATOR_CLASS);
    if (authConfig == null) {
        authConfig = new AuthenticatorConfig();
        authConfig.setParameterMap(new HashMap());
    }
    return authConfig;
}
 
Example #30
Source File: AbstractApplicationAuthenticator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected void publishAuthenticationStepAttempt(HttpServletRequest request, AuthenticationContext context,
                                              User user, boolean success) {

    AuthenticationDataPublisher authnDataPublisherProxy = FrameworkServiceDataHolder.getInstance()
            .getAuthnDataPublisherProxy();
    if (authnDataPublisherProxy != null && authnDataPublisherProxy.isEnabled(context)) {
        boolean isFederated = this instanceof FederatedApplicationAuthenticator;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(FrameworkConstants.AnalyticsAttributes.USER, user);
        if (isFederated) {
            // Setting this value to authentication context in order to use in AuthenticationSuccess Event
            context.setProperty(FrameworkConstants.AnalyticsAttributes.HAS_FEDERATED_STEP, true);
            paramMap.put(FrameworkConstants.AnalyticsAttributes.IS_FEDERATED, true);
            paramMap.put(FrameworkConstants.AUTHENTICATOR, getName());
            if (user != null) {
                user.setTenantDomain(context.getTenantDomain());
            }
        } else {
            // Setting this value to authentication context in order to use in AuthenticationSuccess Event
            context.setProperty(FrameworkConstants.AnalyticsAttributes.HAS_LOCAL_STEP, true);
            paramMap.put(FrameworkConstants.AnalyticsAttributes.IS_FEDERATED, false);
        }
        Map<String, Object> unmodifiableParamMap = Collections.unmodifiableMap(paramMap);
        if (success) {
            authnDataPublisherProxy.publishAuthenticationStepSuccess(request, context,
                    unmodifiableParamMap);

        } else {
            authnDataPublisherProxy.publishAuthenticationStepFailure(request, context,
                    unmodifiableParamMap);
        }
    }
}