Spring Webflow 2.5, Spring Security 5.1, ICEfaces 3.3

Table of Contents

Spring Web Flow 2.5, Spring Security 5.1, and ICEfaces 3.3

  Name Size Creator (Last Modifier) Creation Date Last Mod Date Comment  
ZIP Archive spring-webflow-booking.zip 6.92 MB Mircea Toma Oct 22, 2020 Oct 22, 2020  

About Spring Web Flow

Spring Web Flow is a library that extends Spring MVC to user defined "controllers using a domain-specific-language." Web Flow is appropriately used when several actions need to be performed in order for a greater action to be performed (booking a hotel, or a flight for instance).

About Spring Security

Spring Security 5.1 provides an API for configuring authentication and authorization. Authentication is possible against any number of repositories and databases. Authorization is applied at either the web resource level using Servlet Filters and/or at the business/service method level using aspects and annotations.

Go directly to the portion of this tutorial dealing with Spring Security 5.1 configuration.

About This Tutorial

This tutorial borrows heavily on existing JSF tutorials for Spring Web Flow, and is an evolution of the tutorial for integrating ICEfaces 3.x with Spring Web Flow 2.3.1.

The purpose of this tutorial is to demonstrate how application developers can use both Spring Webflow 2.5 and ICEfaces 3.3.0 in the same application. Both technologies leverage the Servlet API. Understanding how the various parts of the web.xml file are organized to accomodate both frameworks is essential to understanding this tutorial and being able to extend it to meet your own requirements.

This tutorial uses Spring Web Flow 2.5, Spring Security 5.1, Spring Core 5.1, JSF 2.2.16 and ICEfaces 3.3.0_P07. Additional libraries are needed to support these frameworks and have been listed as dependencies in the tutorial's pom.xml file.

Tutorial Use Case

The simple business case for this tutorial is the Spring Web Flow standard "booking application". Users can search for hotels and, after authenticating, book a room. Authenticated users can also review their bookings. This tutorial borrows heavily from the Spring Web Flow sample booking application.

Issue with null ViewId and WindowID

There is an issue with the Spring implementation of the Lifecycle that affects the operation of ICEfaces. The ICEfaces BridgeSetup class uses a JSF PhaseListener to restore certain scope variables into the request map. Spring webflow applications, by default, use a POST->Redirect->GET pattern for navigation, but during the subsequent GET operation, the Spring lifecycle implementation does not appear to be executing the phase listeners during the RESTORE_VIEW phase. Side effects of this problem are the following symptoms:

1) Console messages of the following form:

SEVERE - Missing view ID attribute. Request map cleared prematurely.

SEVERE - Missing window ID attribute. Request map cleared prematurely.

2) NPE trying to rewrite a null viewID into the document:

java.lang.NullPointerException
at org.icefaces.impl.util.DOMUtils.isWhitespaceText(DOMUtils.java:394)
at org.icefaces.impl.util.DOMUtils.printNode(DOMUtils.java:351)
at org.icefaces.impl.util.DOMUtils.printNode(DOMUtils.java:355)
at org.icefaces.impl.util.DOMUtils.printNode(DOMUtils.java:355)

While the booking tutorial does not take advantage of windowScope, it is clear that functionality is reduced. There is a solution, and that is to use a WebflowListener to duplicate the missing PhaseListener functionality. The spring-booking-tutorial uses the com.icesoft.spring.security.WebflowListener (which is an instance of FlowExecutionListenerAdapter) class to this end. You can download a copy of this WebflowListener directly from the link above, and it is also contained and configured in the tutorial. Configuration of the WebflowListener is shown in the webflow-config.xml configuration section below.

Building the Tutorial WAR

Follow the general instructions for building any of the tutorials.


Configuration Areas

There isn't a perfect delineation between the Spring Web MVC, Web Flow and Security configurations, but they are mostly separated into their own separate files, with each requiring some entries in the web.xml.

  1. Configure web.xml for Spring (Core, Web Flow, and Security)
  2. Configure web-application-config.xml
  3. Configure webflow-config.xml
  4. Configure webmvc-config.xml
  5. Configure security-config.xml
  6. Configure data-access-config.xml

Part 1: Configure web.xml for Spring

The web.xml below provides configuration parameters for JSF, filter configurations for Spring security, Spring and JSF Servlet declarations and listeners.

web.xml
<web-app version="3.0"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_0.xsd">

        <!-- Enables JSF debug output during development -->
        <context-param>
            <param-name>javax.faces.PROJECT_STAGE</param-name>
            <param-value>Development</param-value>
        </context-param>

        <!-- Best practice with ICEfaces -->
        <context-param>
            <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
            <param-value>server</param-value>
        </context-param>

        <!-- Causes Facelets to refresh templates during development -->
        <context-param>
            <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
            <param-value>1</param-value>
        </context-param>

        <!-- Use JSF view templates saved as *.xhtml, for use with Facelets -->
        <context-param>
            <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
            <param-value>.xhtml</param-value>
        </context-param>

        <!-- The master configuration file for this Spring web application -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/web-application-config.xml</param-value>
        </context-param>

        <!-- Declare Spring Security Facelets tag library -->
        <context-param>
            <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
            <param-value>/WEB-INF/springsecurity.taglib.xml</param-value>
        </context-param>

        <!-- Enforce UTF-8 Character Encoding -->
        <filter>
            <filter-name>charEncodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>

        <filter-mapping>
            <filter-name>charEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

        <!-- Enables Spring Security -->
        <filter>
            <filter-name>springSecurityFilterChain</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        </filter>

        <filter-mapping>
            <filter-name>springSecurityFilterChain</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

        <!-- Loads the Spring web application context -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

        <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
        <servlet>
            <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value></param-value>
            </init-param>
            <load-on-startup>2</load-on-startup>
        </servlet>

        <!-- Map all /spring requests to the Dispatcher Servlet for handling -->
        <servlet-mapping>
            <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
            <url-pattern>/spring/*</url-pattern>
        </servlet-mapping>

        <!-- Faces Servlet -->
        <servlet>
            <servlet-name>Faces Servlet</servlet-name>
            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        </servlet>

        <!-- Faces Servlet Mapping -->
        <servlet-mapping>
            <servlet-name>Faces Servlet</servlet-name>
            <url-pattern>*.jsf</url-pattern>
        </servlet-mapping>

        <!-- Resolve the missing PNG entry issue on old servers such as WAS7 -->
        <mime-mapping>
            <extension>png</extension>
            <mime-type>image/png</mime-type>
        </mime-mapping>

        <!-- Welcome File Configuration -->
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>

</web-app>

Part 2: Configure web-application-config.xml

The master configuration file for Spring, as referenced in the web.xml by the contextConfigLocation context-param. This file imports all the other Spring configuration files, to better separate the separate concerns into smaller more manageable files, for webmvc, webflow, database, security.

/WEB-INF/config/web-application-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- Scans for application @Components to deploy -->
	<context:component-scan base-package="org.springframework.webflow.samples.booking" />

	<!-- Imports the configurations of the different infrastructure systems of the application -->
	<import resource="webmvc-config.xml" />
	<import resource="webflow-config.xml" />
	<import resource="data-access-config.xml" />
	<import resource="security-config.xml" />
</beans>

Part 3: Configure webflow-config.xml

This step provides an overview of what needs to go into the Spring Web Flow configuration file to integrate well with ICEfaces 3.x. The configuration directs Spring Web Flow to look in the /WEB-INF/flows/*/-flow.xml pattern for web flow declarations. The tutorial application has two of these files which manage the main use case of hostel searching and selection, and the booking case for creating a reservation. There are three FlowExecutionListener declarations: FlowFacesContextLifecycleListener, for managing the FacesContext; SecurityFlowExecutionListener, for security integration; and our WebflowListener, for JSF viewId and ICEfaces windowId management.

/WEB-INF/config/webflow-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:webflow="http://www.springframework.org/schema/webflow-config"
       xmlns:faces="http://www.springframework.org/schema/faces"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd
           http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces.xsd">

	<!-- Executes flows: the central entry point into the Spring Web Flow system -->
	<webflow:flow-executor id="flowExecutor">
		<webflow:flow-execution-listeners>
			<webflow:listener ref="facesContextListener"/>
			<webflow:listener ref="securityFlowExecutionListener" />
            <webflow:listener ref="icefacesFlowListener" />
		</webflow:flow-execution-listeners>
	</webflow:flow-executor>

	<!-- The registry of executable flow definitions -->
	<webflow:flow-registry id="flowRegistry" flow-builder-services="facesFlowBuilderServices" base-path="/WEB-INF/flows">
		<webflow:flow-location-pattern value="/**/*-flow.xml" />
	</webflow:flow-registry>

	<!-- Configures the Spring Web Flow JSF integration -->
	<faces:flow-builder-services id="facesFlowBuilderServices" development="true" />

	<!-- Installs a listener that creates and releases the FacesContext for each request. -->
	<bean id="facesContextListener" class="org.springframework.faces.webflow.FlowFacesContextLifecycleListener"/>

	<!-- Installs a listener to apply Spring Security authorities -->
	<bean id="securityFlowExecutionListener" class="org.springframework.webflow.security.SecurityFlowExecutionListener" />

  <!-- Set the viewId and windowId after a POST-Redirect-GET -->
  <bean id="icefacesFlowListener" class="com.icesoft.spring.security.WebflowListener" />
</beans>

Part 4: Configure webmvc-config.xml

This configuration file includes the basic setup of resolving request paths to flow and view definitions, and resolving their Facelet view definition files. It declares the relevant JSF view and controller objects from Spring MVC, and JSF flow handler from Spring Web Flow.

/WEB-INF/config/webmvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:faces="http://www.springframework.org/schema/faces"
       xsi:schemaLocation="
       	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       	http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces.xsd">

	<faces:resources />

	<!-- Maps request paths to flows in the flowRegistry; e.g. a path of /hotels/booking looks for a flow with id "hotels/booking" -->
	<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
		<property name="order" value="1"/>
		<property name="flowRegistry" ref="flowRegistry" />
		<property name="defaultHandler">
			<!-- If no flow match, map path to a view to render; e.g. the "/intro" path would map to the view named "intro" -->
			<bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
		</property>
	</bean>

	<!-- Maps logical view names to Facelet templates in /WEB-INF (e.g. 'search' to '/WEB-INF/search.xhtml' -->
	<bean id="faceletsViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.faces.mvc.JsfView"/>
		<property name="prefix" value="/WEB-INF/" />
		<property name="suffix" value=".xhtml" />
	</bean>

	<!-- Dispatches requests mapped to org.springframework.web.servlet.mvc.Controller implementations -->
	<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />

	<!-- Dispatches requests mapped to flows to FlowHandler implementations -->
	<bean class="org.springframework.faces.webflow.JsfFlowHandlerAdapter">
		<property name="flowExecutor" ref="flowExecutor" />
	</bean>

</beans>

Part 5: Configure security-config.xml

Configuring Spring Security to work properly with ICEfaces 3 requires configurations not included in other JSF-based Spring Webflow tutorials. This is due to the design decision to leverage Spring Security's configurable "redirectStrategy" property. We explicitly configure the redirectStrategy used by Spring Security to send AJAX redirects if the request is AJAX driven (contains an AJAX header).

/WEB-INF/config/security-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-4.2.xsd">

    <!-- Configure Spring Security -->
    <http auto-config="true"
          use-expressions="true">

        <form-login login-page="/spring/login"
                    login-processing-url="/spring/loginProcess"
                    default-target-url="/spring/main" always-use-default-target="true"
                    authentication-failure-url="/spring/login?login_error=1" />

        <!-- When using custom filters, please make sure the positions do not conflict with default filters.
            Alternatively you can disable the default filters by removing the corresponding child elements from
            http and avoiding the use of http auto-config='true'. -->

        <custom-filter ref="exceptionTranslationFilter" before="FILTER_SECURITY_INTERCEPTOR" />


        <logout logout-url="/spring/logout" logout-success-url="/spring/logoutSuccess" invalidate-session="true"/>
        <intercept-url pattern="/secure" method="POST" access="hasRole('ROLE_SUPERVISOR')"/>
        <csrf disabled="true"/>
    </http>

    <beans:bean id="passwordEncoder" class="org.springframework.security.crypto.password.MessageDigestPasswordEncoder">
            <beans:constructor-arg value="MD5"/>
    </beans:bean>

    <!--
		Define local authentication provider, a real app would use an external provider (JDBC, LDAP, CAS, etc)

		usernames/passwords are:
			keith/melbourne
			erwin/leuven
			jeremy/atlanta
			scott/rochester
	-->
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="keith" password="417c7382b16c395bc25b5da1398cf076"
                      authorities="ROLE_USER, ROLE_SUPERVISOR"/>
                <user name="erwin" password="12430911a8af075c6f41c6976af22b09"
                      authorities="ROLE_USER, ROLE_SUPERVISOR"/>
                <user name="jeremy" password="57c6cbff0d421449be820763f03139eb" authorities="ROLE_USER"/>
                <user name="scott" password="942f2339bf50796de535a384f0d1af3e" authorities="ROLE_USER"/>
            </user-service>
            <password-encoder ref="passwordEncoder"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="sessionManagementFilter"
            class="org.springframework.security.web.session.SessionManagementFilter">
        <beans:constructor-arg name="securityContextRepository" ref="httpSessionSecurityContextRepository" />
        <beans:property name="invalidSessionStrategy" ref="jsfInvalidSessionStrategy" />
    </beans:bean>

    <beans:bean id="jsfInvalidSessionStrategy" class="com.icesoft.spring.security.JsfInvalidSessionStrategy">
        <beans:constructor-arg name="invalidSessionUrl" value="/general/logins/sessionExpired.jsf" />
    </beans:bean>


    <!-- http://static.springsource.org/spring-security/site/docs/3.1.x/reference/core-web-filters.html -->
    <beans:bean id="exceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
      <beans:property name="accessDeniedHandler" ref="jsfAccessDeniedHandler"/>
      <beans:constructor-arg name="authenticationEntryPoint" ref="authenticationEntryPoint"/>
    </beans:bean>

    <beans:bean id="jsfAccessDeniedHandler" class="com.icesoft.spring.security.JsfAccessDeniedHandler">
        <beans:property name="loginPath" value="/spring/login" />
        <beans:property name="contextRelative" value="true" />
    </beans:bean>

    <beans:bean  id="authenticationEntryPoint" class="com.icesoft.spring.security.JsfLoginUrlAuthenticationEntryPoint">
        <beans:property name="loginFormUrl" value="/spring/login"/>
        <beans:property name="redirectStrategy" ref="jsfRedirectStrategy" />
    </beans:bean >


    <beans:bean id="jsfRedirectStrategy" class="com.icesoft.spring.security.JsfRedirectStrategy"/>
    <beans:bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>

</beans:beans>

Part 6: Configure data-access-config.xml

Configured to use HSQLDB via Hibernate.

/WEB-INF/config/data-access-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Instructs Spring to perform declarative transaction management on annotated classes -->
    <tx:annotation-driven />

    <!-- Drives transactions using local JPA APIs -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- Creates a EntityManagerFactory for use with the Hibernate JPA provider and a simple in-memory data source populated with test data -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
    </bean>

    <!-- Deploys a in-memory "booking" datasource populated -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
        <property name="url" value="jdbc:hsqldb:mem:booking" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>
</beans>

Resources

Spring Web Flow 2.5 Documentation

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

© Copyright 2021 ICEsoft Technologies Canada Corp.