Barebones Spring MVC part 5: Security

August 19, 2010

A web application would seldom be complete without at least a minimal security layer to prohibit unauthenticated access to protected resources.

This example builds upon part 1: core to introduce basic security by adding a form-based login page using Spring Security.

The following changes are required:

  1. Add Spring Security to the Maven POM.
  2. Add Spring Security's DelegatingFilterProxy to the web deployment descriptor.
  3. Create an aplication-level Spring context containing Spring Security configuration..

Spring Security's DelegatingFilterProxy is essentially a J2EE Filter which nominally handles all requests and determines how to allow or reject access.

web.xml:

<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>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-mvc-security.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Spring's ContextLoaderListener is needed because there is now a parent Spring context which is inherited by the spring-mvc context of before. The contextConfigLocation parameter specifies the location of the new parent configuration file.

spring-mvc-security.xml:

<!-- Enable Spring Security with HTTP basic authentication. -->
<http auto-config="true">
    <http-basic />
    <intercept-url pattern="/**" access="ROLE_USER" />
    <form-login />
</http>

<!-- An AuthenticationProvider with sample users and roles. -->
<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="jmcdoe" password="jmcdoe" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

This nearly minimal configuration sets up an in-memory repository of roles, and enforces access to every resource against this repository. Here, a form-based login page is provided by Spring.