Spring Security With Web MVC Example

[Updated: Jul 7, 2017, Created: Jul 7, 2017]

In this example, we will learn how to use Spring security in a Spring Web MVC application. We will do in memory authentication of Spring security.

Maven dependencies

pom.xml

<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>4.2.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>4.2.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.3.9.RELEASE</version>
</dependency>
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
</dependency>

Java Config class

@Configuration
@EnableWebSecurity
@EnableWebMvc
@ComponentScan
public class AppConfig extends WebSecurityConfigurerAdapter {

  @Override
  public void configure(AuthenticationManagerBuilder builder)
          throws Exception {
      builder.inMemoryAuthentication()
             .withUser("joe")
             .password("123")
             .roles("ADMIN");
  }

  @Bean
  public ViewResolver viewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      viewResolver.setPrefix("/WEB-INF/views/");
      viewResolver.setSuffix(".jsp");
      return viewResolver;
  }
}

DispatcherServlet initializer

public class WebAppInitializer extends
      AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
      return new Class<?>[]{AppConfig.class};
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
      return null;
  }

  @Override
  protected String[] getServletMappings() {
      return new String[]{"/"};
  }
}

Initializing Security components

We still need to extend AbstractSecurityWebApplicationInitializer to initialize the security filter.

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

A controller

@Controller
public class ExampleController {
  @RequestMapping("/app")
  @ResponseBody
  public String handleRequest() {
      return "welcome to the app";
  }

  @RequestMapping("/page")
  public String handleRequest2(ModelMap map) {
      map.addAttribute("time", LocalDateTime.now().toString());
      return "my-page";
  }
}

The JSP page

src/main/webapp/WEB-INF/views/my-page.jsp

<html lang="en">
<body>
<h2>Spring Security Example</h2>
<p>Time: ${time}</p>
</body>
</html>

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Accessing URI '/app' (Accessing any resource for the first time will show Spring authentication form):

After submitting user name and password as we set up in our AppConfig class:

Accessing URI '/page':

Example Project

Dependencies and Technologies Used :

  • spring-security-web 4.2.3.RELEASE: spring-security-web.
  • spring-security-config 4.2.3.RELEASE: spring-security-config.
  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Spring Security with Web MVC Example Select All Download
  • spring-security-with-mvc-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views

See Also