Spring Security Quick Start Example

[Updated: Jul 14, 2017, Created: Jun 30, 2017]

This is a quick start example of Spring security. We will see how to do in-memory authentication in a web application. This web application will run in a servlet container with static html pages. To keep it simple, we are not going to use Spring MVC or other spring modules in this example.

Maven dependencies



javax.servlet-api dependency is needed because spring-security-web contains servlet filters and other servlet based infrastructure code.

Java Config class

public class AppConfig extends WebSecurityConfigurerAdapter {

  public void configure(AuthenticationManagerBuilder builder)
          throws Exception {

Above configuration will require authentication to every URL in our application. It will also generate a login form for us.

Initializing Java Config

We have to extend Abstract Security Web Application Initializer to initialize our Java config class:

public class AppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
  public AppSecurityInitializer() {

Above code will also register necessary servlet filters for authentication process. Abstract Security Web Application Initializer is based on ServletContainerInitializer pattern.

Static pages


<!DOCTYPE html>
<html lang="en">
<h2>Spring Security Example</h2>
<a href="page2.html">Page 2</a>


<!DOCTYPE html>
<html lang="en">
<h2>Page 2</h2>
<a href="index.html">main page</a>

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

mvn tomcat7:run-war


Accessing any page first time will show Spring authentication form:

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

Click on Page 2 link:

The example application will require authentication again on the session expiration.

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.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Web Security Quick Start Select All Download
  • web-security-getting-started-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp

See Also