Home > Spring, Spring Security > How to configure Spring Security using annotations

How to configure Spring Security using annotations


As far as integrating Spring Security into a Spring enabled project, there are 2 possibilities, both presented in detail on-line, in the reference documentation:

1. using Java Configuration, see details here http://docs.spring.io/spring-security/site/docs/3.2.3.RELEASE/reference/htmlsingle/#jc. This is very useful for applications using the Servlet 3.0 specification, which already register all their servlets by using annotations and which don’t have a web.xml.

2. using XML Configuration, see details here http://docs.spring.io/spring-security/site/docs/3.2.3.RELEASE/reference/htmlsingle/#ns-getting-started. This approach is very useful for applications using specification preceeding Servlet 3.0 or simply for those who use the web.xml for configuration.

My use case is a combination of the both. I have created a web application using Spring and Spring MVC. I have configured my DispatcherServlet in the application’s web.xml. I wanted to use only Java configuration, so I’ve been using an AnnotationConfigWebApplicationContext. When I tried to add Spring Security, I wanted to keep the same approach: Spring Security filterregistered in the web.xml, while all the configuration code would be written in Java. The problem was that the reference documentation doesn’t show how to build such a project (or maybe I missed it). Googleing for a how-to also didn’t return any satisfactory results.

My setup right now is: eclipse kepler together with the m2eclipse plug-in, Java 1.7, apache tomcat 7.0.53, maven 3.2.1. I have built a simple project using Spring MVC, with only one page, called welcome.jsp, with a simple controller for it, which does nothing but return the correct view name.

In web.xml, I first registered the ContextLoaderListener. This creates a top-level Spring application context. In order to customize the type of the application context, I’ve used the contextClass and contextConfigLocation parameters.

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>vlad.carcu.spring.security.xml.config</param-value>
</context-param>
<context-param>
	<param-name>contextClass</param-name>
	<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>

I placed in the configured package my configuration classes. The first one is for Spring and it configures the view resolved, together with enabling MVC and bean auto-discovery.

package vlad.carcu.spring.security.xml.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@ComponentScan(basePackages = { "vlad.carcu.spring.security.xml" })
@EnableWebMvc
public class ApplicationConfiguration {

	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
		internalResourceViewResolver.setViewClass(JstlView.class);
		internalResourceViewResolver.setPrefix("/jsp/");
		internalResourceViewResolver.setSuffix(".jsp");
		return internalResourceViewResolver;
	}

}

The next one is the Spring Security configuration. It specifies in-memory authentication, with the user ‘user’ and the password ‘password’. Additionally, it changes the default URL to which the login page redirects to the defined welcome page.

package vlad.carcu.spring.security.xml.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		super.configure(http);
		http.formLogin().defaultSuccessUrl("/welcome", true);
	}
	
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {
		auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
	}
}

Next, I registered the DispatcherServlet. When started, it will create a new application context, which will inherit from the top-level one. The trick here is to either specify a location where you have web beans defined, or, use an empty location. Not having the contextConfigLocation paramter specified, the DispatcherServlet will look by default for a file called servletname-servlet.xml in your WEB-INF directory.

<servlet>
	<servlet-name>dispatcher</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>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>dispatcher</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

Finally, I registered the Spring Security filter. This filter will have access to the top-level context, but it will have no knowledge whatsoever regarding the context created by the DispatcherServlet.

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

After running the project on the server, open http://localhost:8080/spring.security.xml. It will automatically redirect to http://localhost:8080/spring.security.xml/login. This is a page generated automatically by Spring Security.
1

Introducing the correct username and password, and clicking Login, you will be redirected to the welcome page.

2

You can find the full archive of the project here: https://www.dropbox.com/s/9jq0gdsvf0cv667/spring.security.xml.7z.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s