Extending CAS Webflow

The objective of this guide is to better describe how CAS utilizes Spring Webflow to accommodate various authentication flows. Please remember that this is NOT to teach one how Spring Webflow itself works internally. If you want to learn more about Spring Webflow and understand the internals of actions, states, decisions and scopes please see this guide.

CAS by default operates on the following core webflow configuration files:

Flow Description
login Authentication flow for login attempts.
logout Authentication flow for logout attempts.
pswdreset Password management and password reset flow.
account Account management and profile flow..

The above flows present a minimal structure for what CAS needs at its core to handle login and logout flows. It is important to note that at runtime many other actions and states are injected into either of these flows dynamically depending on the CAS configuration and presence of feature modules. Also note that each feature module itself may dynamically present other opinionated subflow configuration files that are automagically picked up at runtime.

Modifying Webflow

In modest trivial cases, you may be able to overlay and modify the core flow configuration files to add or override the desired behavior. Again, think very carefully before introducing those changes into your deployment environment. Avoid making ad-hoc changes to the webflow as much as possible and consider how the change you have in mind might be more suitable as a direct contribution to the CAS project itself so you can just take advantage of its configuration and NOT its maintenance.

To learn how to introduce new actions and state into a Spring Webflow, please see this guide.

:information_source: Speak Up

If you find something that is broken where the webflow auto-configuration strategy fails to deliver as advertised, discuss that with the project community and submit a patch that corrects the bug or adds the desired behavior as a modest enhancement. Avoid one-off changes and make the change where the change belongs.

In more advanced cases where you may need to take a deep dive and alter core CAS behavior conditionally, you would need to take advantage of the CAS APIs to deliver changes. Using the CAS APIs directly does present the following advantages at some cost:

  • Changes are all scoped to Java (Groovy, Kotlin, Clojure, etc).
  • You have the full power of Java to dynamically and conditionally augment the Spring Webflow.
  • Your changes are all self-contained.
  • Changes are now part of the CAS APIs and they will be compiled. Breaking changes on upgrades, if any, should be noticed immediately at build time.

Java

This is the most traditional yet most powerful method of dynamically altering the webflow internals. You will be asked to write components that auto-configure the webflow and inject themselves into the running CAS application context only to be executed at runtime.

At a minimum, your overlay will need to include the following modules:

1
2
3
4
5
<dependency>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-server-core-webflow</artifactId>
    <version>${cas.version}</version>
</dependency>
1
implementation "org.apereo.cas:cas-server-core-webflow:${project.'cas.version'}"
1
2
3
4
5
6
7
8
9
dependencyManagement {
    imports {
        mavenBom "org.apereo.cas:cas-server-support-bom:${project.'cas.version'}"
    }
}

dependencies {
    implementation "org.apereo.cas:cas-server-core-webflow"
}
1
2
3
4
5
6
7
8
9
10
dependencies {
    /*
        The following platform references should be included automatically and are listed here for reference only.

        implementation enforcedPlatform("org.apereo.cas:cas-server-support-bom:${project.'cas.version'}")
        implementation platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES)
        
    */
    implementation "org.apereo.cas:cas-server-core-webflow"
}

Design

Design your dynamic webflow configuration agent that alters the webflow using the following form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class SomethingWebflowConfigurer extends AbstractCasWebflowConfigurer {
    public SomethingWebflowConfigurer(FlowBuilderServices flowBuilderServices,
                                      FlowDefinitionRegistry flowDefinitionRegistry,
                                      ApplicationContext applicationContext,
                                      CasConfigurationProperties casProperties) {
        super(flowBuilderServices, flowDefinitionRegistry, applicationContext, casProperties);
    }

    @Override
    protected void doInitialize() throws Exception {
        var flow = super.getLoginFlow();
        // Magic happens; Call 'super' to see 
        // what you have access to and alter the flow.
    }
}

The parent class, AbstractCasWebflowConfigurer, providers a lot of helper methods and utilities in a DSL-like fashion to hide the complexity of Spring Webflow APIs to make customization easier.

Register

You will then need to register your newly-designed component into the CAS application runtime:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package org.example.something;

@AutoConfiguration
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class SomethingConfiguration implements CasWebflowExecutionPlanConfigurer {

    @Autowired
    private CasConfigurationProperties casProperties;

    @Autowired
    @Qualifier(CasWebflowConstants.BEAN_NAME_LOGIN_FLOW_DEFINITION_REGISTRY)
    private FlowDefinitionRegistry loginFlowDefinitionRegistry;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private FlowBuilderServices flowBuilderServices;

    @ConditionalOnMissingBean(name = "somethingWebflowConfigurer")
    @Bean
    public CasWebflowConfigurer somethingWebflowConfigurer() {
        return new SomethingWebflowConfigurer(flowBuilderServices,
            loginFlowDefinitionRegistry, applicationContext, casProperties);
    }

    @Override
    public void configureWebflowExecutionPlan(final CasWebflowExecutionPlan plan) {
        plan.registerWebflowConfigurer(somethingWebflowConfigurer());
    }
}

Configuration classes need to be registered with CAS via the strategy outlined here.

:information_source: To Build & Beyond

Note that compiling configuration classes and any other piece of Java code that is put into the CAS Overlay may require additional CAS modules and dependencies on the classpath. You will need to study the CAS codebase and find the correct modules that contain the components you need, such as CasWebflowConfigurer and others.

See this guide for more info.

Groovy

You may configure CAS to alter and auto-configure the webflow via a Groovy script. This is the less elaborate option where you have modest access to CAS APIs that allow you alter the webflow. However, configuration and scaffolding of the overlay and required dependencies is easier as all is provided by CAS at runtime.

:warning: Stop Coding

Remember that APIs provided here, specifically executed as part of the Groovy script are considered implementations internal to CAS mostly. They may be added or removed with little hesitation which means changes may break your deployment and upgrades at runtime. Remember that unlike Java classes, scripts are not statically compiled when you build CAS and you only may observe failures when you do in fact turn on the server and deploy. Thus, choose this option with good reason and make sure you have thought changes through before stepping into code.

Configuration

To prepare CAS to support and integrate with Apache Groovy, please review this guide.

The following settings and properties are available from the CAS configuration catalog:

The configuration settings listed below are tagged as Required in the CAS configuration metadata. This flag indicates that the presence of the setting may be needed to activate or affect the behavior of the CAS feature and generally should be reviewed, possibly owned and adjusted. If the setting is assigned a default value, you do not need to strictly put the setting in your copy of the configuration, but should review it nonetheless to make sure it matches your deployment expectations.

  • cas.webflow.groovy.location=
  • The location of the resource. Resources can be URLs, or files found either on the classpath or outside somewhere in the file system.

    In the event the configured resource is a Groovy script, specially if the script set to reload on changes, you may need to adjust the total number of inotify instances. On Linux, you may need to add the following line to /etc/sysctl.conf: fs.inotify.max_user_instances = 256.

    You can check the current value via cat /proc/sys/fs/inotify/max_user_instances.

    In situations and scenarios where CAS is able to automatically watch the underlying resource for changes and detect updates and modifications dynamically, you may be able to specify the following setting as either an environment variable or system property with a value of false to disable the resource watcher: org.apereo.cas.util.io.PathWatcherService.

    org.apereo.cas.configuration.model.core.web.flow.GroovyWebflowProperties.

    How can I configure this property?

  • cas.webflow.login-decorator.groovy.location=
  • The location of the resource. Resources can be URLs, or files found either on the classpath or outside somewhere in the file system.

    In the event the configured resource is a Groovy script, specially if the script set to reload on changes, you may need to adjust the total number of inotify instances. On Linux, you may need to add the following line to /etc/sysctl.conf: fs.inotify.max_user_instances = 256.

    You can check the current value via cat /proc/sys/fs/inotify/max_user_instances.

    In situations and scenarios where CAS is able to automatically watch the underlying resource for changes and detect updates and modifications dynamically, you may be able to specify the following setting as either an environment variable or system property with a value of false to disable the resource watcher: org.apereo.cas.util.io.PathWatcherService.

    org.apereo.cas.configuration.model.core.web.flow.GroovyWebflowLoginDecoratorProperties.

    How can I configure this property?

    The configuration settings listed below are tagged as Optional in the CAS configuration metadata. This flag indicates that the presence of the setting is not immediately necessary in the end-user CAS configuration, because a default value is assigned or the activation of the feature is not conditionally controlled by the setting value. In other words, you should only include this field in your configuration if you need to modify the default value or if you need to turn on the feature controlled by the setting.

  • cas.webflow.groovy.actions=
  • This setting allows one to provide an alternative implementation to Spring Webflow's actions as implemented in Groovy. See CAS documentation on the outline of the script as well as any inputs and outputs expected. This setting is defined as map, where the key is expected to be the name/identifier of the bean that supplies the Spring Webflow action and the value is a resource path to the Groovy script (i.e. file:/path/to/Script.groovy) that shall be executed when the action is called upon by CAS and the Spring Webflow execution runtime. You will need to examine the CAS codebase to locate the proper bean identifier for the action in question. Note that Groovy scripts entirely supplant the CAS implementation for Spring Webflow actions and must be designed carefully and in compliance with the rest of the webflow orchestration.

    org.apereo.cas.configuration.model.core.web.flow.GroovyWebflowProperties.

    How can I configure this property?

    CAS takes advantage of Apache Groovy in forms of either embedded or external scripts that allow one to, by default, dynamically build constructs, attributes, access strategies and a lot more. To activate the functionality described here, you may need to prepare CAS to support and integrate with Apache Groovy.

    Please review this guide to configure your build.

    Configuration Metadata

    The collection of configuration properties listed in this section are automatically generated from the CAS source and components that contain the actual field definitions, types, descriptions, modules, etc. This metadata may not always be 100% accurate, or could be lacking details and sufficient explanations.

    Be Selective

    This section is meant as a guide only. Do NOT copy/paste the entire collection of settings into your CAS configuration; rather pick only the properties that you need. Do NOT enable settings unless you are certain of their purpose and do NOT copy settings into your configuration only to keep them as reference. All these ideas lead to upgrade headaches, maintenance nightmares and premature aging.

    YAGNI

    Note that for nearly ALL use cases, declaring and configuring properties listed here is sufficient. You should NOT have to explicitly massage a CAS XML/Java/etc configuration file to design an authentication handler, create attribute release policies, etc. CAS at runtime will auto-configure all required changes for you. If you are unsure about the meaning of a given CAS setting, do NOT turn it on without hesitation. Review the codebase or better yet, ask questions to clarify the intended behavior.

    Naming Convention

    Property names can be specified in very relaxed terms. For instance cas.someProperty, cas.some-property, cas.some_property are all valid names. While all forms are accepted by CAS, there are certain components (in CAS and other frameworks used) whose activation at runtime is conditional on a property value, where this property is required to have been specified in CAS configuration using kebab case. This is both true for properties that are owned by CAS as well as those that might be presented to the system via an external library or framework such as Spring Boot, etc.

    :information_source: Note

    When possible, properties should be stored in lower-case kebab format, such as cas.property-name=value. The only possible exception to this rule is when naming actuator endpoints; The name of the actuator endpoints (i.e. ssoSessions) MUST remain in camelCase mode.

    Settings and properties that are controlled by the CAS platform directly always begin with the prefix cas. All other settings are controlled and provided to CAS via other underlying frameworks and may have their own schemas and syntax. BE CAREFUL with the distinction. Unrecognized properties are rejected by CAS and/or frameworks upon which CAS depends. This means if you somehow misspell a property definition or fail to adhere to the dot-notation syntax and such, your setting is entirely refused by CAS and likely the feature it controls will never be activated in the way you intend.

    Validation

    Configuration properties are automatically validated on CAS startup to report issues with configuration binding, specially if defined CAS settings cannot be recognized or validated by the configuration schema. Additional validation processes are also handled via Configuration Metadata and property migrations applied automatically on startup by Spring Boot and family.

    Indexed Settings

    CAS settings able to accept multiple values are typically documented with an index, such as cas.some.setting[0]=value. The index [0] is meant to be incremented by the adopter to allow for distinct multiple configuration blocks.

    Webflow Auto Configuration

    A sample Groovy script follows that aims to locate the CAS login flow and a particular state pre-defined in the flow. If found, a custom action is inserted into the state to execute as soon as CAS enters that state in the flow. While this is a rather modest example, note that the script has the ability to add/remove actions, states, transitions, add/remove subflows, etc.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    
    import java.util.*
    
    import org.apereo.cas.*
    import org.apereo.cas.web.*
    import org.apereo.cas.web.support.*
    import org.apereo.cas.web.flow.*
    
    import org.springframework.webflow.*
    import org.springframework.webflow.engine.*
    import org.springframework.webflow.execution.*
    
    Object run(final Object... args) {
        def (webflow,springApplicationContext,logger) = args
    
        logger.info("Configuring webflow context...")
    
        def loginFlow = webflow.getLoginFlow()
        if (webflow.containsFlowState(loginFlow, CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM)) {
            logger.info("Found state that initializes the login form")
    
            def state = webflow.getState(loginFlow, CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM, ActionState.class)
            logger.info("The state id is {}", state.id)
    
            state.getEntryActionList().add({ requestContext ->
                def flowScope = requestContext.flowScope
                def httpRequest = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext)
    
                logger.info("Action executing as part of ${state.id}. Stuff happens...")
                return new Event(this, "success")
            })
    
            logger.info("Added action to ${state.id}'s entry action list")
        }
    
        return true
    }
    

    The parameters passed are as follows:

    Parameter Description
    webflow The object representing a facade on top of Spring Webflow APIs.
    springApplicationContext The Spring application context.
    logger Logger object for issuing log messages such as logger.info(...).

    Webflow Actions

    Webflow operations are typically handled via Action components that are implemented and registered with the CAS runtime as Bean definitions. While these definitions could be conditionally substituted with an alternative implementation, you also have the option to carry out the action operation via Groovy scripts. In this scenario, you take over the responsibility of action implementation yourself, relieving CAS from providing you with an implementation.

    The following settings and properties are available from the CAS configuration catalog:

    The configuration settings listed below are tagged as Required in the CAS configuration metadata. This flag indicates that the presence of the setting may be needed to activate or affect the behavior of the CAS feature and generally should be reviewed, possibly owned and adjusted. If the setting is assigned a default value, you do not need to strictly put the setting in your copy of the configuration, but should review it nonetheless to make sure it matches your deployment expectations.

    The configuration settings listed below are tagged as Optional in the CAS configuration metadata. This flag indicates that the presence of the setting is not immediately necessary in the end-user CAS configuration, because a default value is assigned or the activation of the feature is not conditionally controlled by the setting value. In other words, you should only include this field in your configuration if you need to modify the default value or if you need to turn on the feature controlled by the setting.

  • cas.webflow.groovy.actions=
  • This setting allows one to provide an alternative implementation to Spring Webflow's actions as implemented in Groovy. See CAS documentation on the outline of the script as well as any inputs and outputs expected. This setting is defined as map, where the key is expected to be the name/identifier of the bean that supplies the Spring Webflow action and the value is a resource path to the Groovy script (i.e. file:/path/to/Script.groovy) that shall be executed when the action is called upon by CAS and the Spring Webflow execution runtime. You will need to examine the CAS codebase to locate the proper bean identifier for the action in question. Note that Groovy scripts entirely supplant the CAS implementation for Spring Webflow actions and must be designed carefully and in compliance with the rest of the webflow orchestration.

    org.apereo.cas.configuration.model.core.web.flow.GroovyWebflowProperties.

    How can I configure this property?

    CAS takes advantage of Apache Groovy in forms of either embedded or external scripts that allow one to, by default, dynamically build constructs, attributes, access strategies and a lot more. To activate the functionality described here, you may need to prepare CAS to support and integrate with Apache Groovy.

    Please review this guide to configure your build.

    Configuration Metadata

    The collection of configuration properties listed in this section are automatically generated from the CAS source and components that contain the actual field definitions, types, descriptions, modules, etc. This metadata may not always be 100% accurate, or could be lacking details and sufficient explanations.

    Be Selective

    This section is meant as a guide only. Do NOT copy/paste the entire collection of settings into your CAS configuration; rather pick only the properties that you need. Do NOT enable settings unless you are certain of their purpose and do NOT copy settings into your configuration only to keep them as reference. All these ideas lead to upgrade headaches, maintenance nightmares and premature aging.

    YAGNI

    Note that for nearly ALL use cases, declaring and configuring properties listed here is sufficient. You should NOT have to explicitly massage a CAS XML/Java/etc configuration file to design an authentication handler, create attribute release policies, etc. CAS at runtime will auto-configure all required changes for you. If you are unsure about the meaning of a given CAS setting, do NOT turn it on without hesitation. Review the codebase or better yet, ask questions to clarify the intended behavior.

    Naming Convention

    Property names can be specified in very relaxed terms. For instance cas.someProperty, cas.some-property, cas.some_property are all valid names. While all forms are accepted by CAS, there are certain components (in CAS and other frameworks used) whose activation at runtime is conditional on a property value, where this property is required to have been specified in CAS configuration using kebab case. This is both true for properties that are owned by CAS as well as those that might be presented to the system via an external library or framework such as Spring Boot, etc.

    :information_source: Note

    When possible, properties should be stored in lower-case kebab format, such as cas.property-name=value. The only possible exception to this rule is when naming actuator endpoints; The name of the actuator endpoints (i.e. ssoSessions) MUST remain in camelCase mode.

    Settings and properties that are controlled by the CAS platform directly always begin with the prefix cas. All other settings are controlled and provided to CAS via other underlying frameworks and may have their own schemas and syntax. BE CAREFUL with the distinction. Unrecognized properties are rejected by CAS and/or frameworks upon which CAS depends. This means if you somehow misspell a property definition or fail to adhere to the dot-notation syntax and such, your setting is entirely refused by CAS and likely the feature it controls will never be activated in the way you intend.

    Validation

    Configuration properties are automatically validated on CAS startup to report issues with configuration binding, specially if defined CAS settings cannot be recognized or validated by the configuration schema. Additional validation processes are also handled via Configuration Metadata and property migrations applied automatically on startup by Spring Boot and family.

    Indexed Settings

    CAS settings able to accept multiple values are typically documented with an index, such as cas.some.setting[0]=value. The index [0] is meant to be incremented by the adopter to allow for distinct multiple configuration blocks.

    :information_source: Note

    You will need to dig up the name of the original action Bean first before you can provide a Groovy substitute. This will require a careful analysis of CAS codebase. Furthermore, please note that not all Spring Webflow actions may be substituted with a Groovy equivalent. Groovy support in this area is a continuous development effort and will gradually improve throughout various CAS releases. Cross-check with the codebase to be sure.

    The outline of the script may be as follows:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    import org.apereo.cas.authentication.principal.*
    import org.apereo.cas.authentication.*
    import org.apereo.cas.util.*
    import org.springframework.webflow.*
    import org.springframework.webflow.action.*
    
    def run(Object[] args) {
        def (requestContext,applicationContext,properties,logger) = args
        logger.info("Handling action...")
        return new EventFactorySupport().event(this, "success")
    }
    

    The outcome of the script should be a Spring Webflow Event. The parameters passed are as follows:

    Parameter Description
    requestContext The object representing the Spring Webflow execution context that carries the HTTP request and response.
    applicationContext The Spring application context.
    properties Reference to CAS configuration properties.
    logger Logger object for issuing log messages such as logger.info(...).