Saturday 15 September 2012

Spring Security Configuration Introduction

This post describes the basic Spring security configuration steps all Spring applications must implement.

Setting Filters

Spring security relies on user request filters. These must be configured in the web.xml file under the contextConfigLocation elements:
<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>

Security Configuration

A <name>-security.xml file must be created in /WEB-INF with this initial structure:
<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-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    ...
</beans:beans>
<name> must be the name of the servlet as configured in web.xml.

Spring configuration can only be performed with XML documents. However, one can mix Java configuration and Spring XML configuration like this when using MVC:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "my.packages")
@ImportResource("WEB-INF/<name>-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {
    ...
}
The above imports the Spring security configuration.

REM: the tutorial available here recommends configuring the <name>-security.xml file in the contextConfigLocation section of web.xml. However, it does not work when using Java configuration. One must use @ImportResource as described above.

Maven Dependencies

The following maven dependencies are required for Spring security:
<properties>
    ...
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>
...
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring.version}</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
</dependency>

For a concrete Spring Security example, click here • More Spring related posts here.

No comments:

Post a Comment