This guide provides instructions on how to add Spring Security to an existing Spring MVC application without the use of XML.

Setting up the sample

This section outlines how to setup a workspace within Spring Tool Suite (STS) so that you can follow along with this guide. The next section outlines generic steps for how to apply Spring Security to your existing application. While you could simply apply the steps to your existing application, we encourage you to follow along with this guide in order to reduce the complexity.

Obtaining the sample project

Extract the Spring Security Distribution to a known location and remember it as SPRING_SECURITY_HOME.

Import the insecuremvc sample application

In order to follow along, we encourage you to import the insecuremvc sample application into your IDE. You may use any IDE you prefer, but the instructions in this guide will assume you are using Spring Tool Suite (STS).

The completed sample application can be found at SPRING_SECURITY_HOME/samples/javaconfig/hellomvc
  • If you do not have STS installed, download STS from https://spring.io/tools

  • Start STS and import the sample application into STS using the following steps:

    • File→Import

    • Existing Maven Projects

    • Click Next >

    • Click Browse…​

    • Navigate to the samples (i.e. SPRING_SECURITY_HOME/samples/xml/insecuremvc) and click OK

    • Click Finish

Running the insecuremvc application

In the following exercise we will be modifying the spring-security-samples-xml-insecuremvc application. Before we make any changes, it is best to verify that the sample works properly. Perform the following steps to ensure that spring-security-samples-xml-insecuremvc works.

  • Right click on the spring-security-samples-xml-insecuremvc application

  • Select Run As→Run on Server

  • Select the latest tc Server

  • Click Finish

Verify the application is working:

  • A page displaying a user’s inbox can be seen at http://localhost:8080/sample/

  • Try clicking on the Compose link and creating a message. The message details should be displayed.

  • Now click on the Inbox link and see the message listed. You can click on the summary link to see the details displayed again.

Securing the application

Before securing your application, it is important to ensure that the existing application works as we did in Running the insecuremvc application. Now that the application runs without security, we are ready to add security to our application. This section demonstrates the minimal steps to add Spring Security to our application.

Updating your dependencies

In order to resolve Spring Security milestones and release candidates add the Spring Milestone repository. For our example, the repository has already been added for you. In the event you were working on another application, you would need to ensure you add the following to your pom:

pom.xml
<repositories>
  <!-- ... possibly other repository elements ... -->
  <repository>
    <id>spring-milestone</id>
    <name>Spring Milestone Repository</name>
    <url>https://repo.spring.io/milestone</url>
  </repository>
</repositories>

In order to use Spring Security you must add the necessary dependencies. For the sample we will add the following Spring Security dependencies:

pom.xml
<dependencies>
  <!-- ... other dependency elements ... -->
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>
</dependencies>

After you have completed this, you need to ensure that STS knows about the updated dependencies by:

  • Right click on the spring-security-samples-xml-insecuremvc application

  • Select Maven→Update project…​

  • Ensure the project is selected, and click OK

Creating your Spring Security configuration

The next step is to create a Spring Security configuration.

  • Right click the spring-security-samples-xml-insecuremvc project in the Package Explorer view

  • Select New→Class

  • Enter org.springframework.security.samples.config for the Package

  • Enter SecurityConfig for the Name

  • Click Finish

  • Replace the file with the following contents:

src/main/java/org/springframework/security/samples/config/SecurityConfig.java
package org.springframework.security.samples.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}
The name of the configureGlobal method is not important. However, it is important to only configure AuthenticationManagerBuilder in a class annotated with either @EnableWebSecurity, @EnableGlobalMethodSecurity, or @EnableGlobalAuthentication. Doing otherwise has unpredictable results.

The SecurityConfig will:

Registering Spring Security with the war

We have created the Spring Security configuration, but we still need to register it with the war. This can be done using the following steps:

  • Right click the spring-security-samples-xml-insecuremvc project the Package Explorer view

  • Select New→Class

  • Enter org.springframework.security.samples.config for the Package

  • Enter MessageSecurityWebApplicationInitializer for the Name

  • Click Finish

  • Replace the file with the following contents:

src/main/java/org/springframework/security/samples/config/MessageSecurityWebApplicationInitializer.java
package org.springframework.security.samples.config;

import org.springframework.security.web.context.*;

public class MessageSecurityWebApplicationInitializer
      extends AbstractSecurityWebApplicationInitializer {
}

The MessageSecurityWebApplicationInitializer will automatically register the springSecurityFilterChain Filter for every URL in your application. If Filters are added within other WebApplicationInitializer instances we can use @Order to control the ordering of the Filter instances.

Verify SecurityConfig is loaded

Just because SecurityConfig exists, does not mean that our Spring application knows about it. In this instance, our Spring root application context is initialized using MessageWebApplicationInitializer which is included with our spring-security-samples-javaconfig-messages project. You can find a snippet of it below:

MessageWebApplicationInitializer.java
public class MessageWebApplicationInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

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

    // ... other overrides ...
}

You will notice it is loading the RootConfiguration class which is also included in our spring-security-samples-javaconfig-messages project.

RootConfiguration.java
@Configuration
@ComponentScan
public class RootConfiguration {
}

The @ComponentScan is loading all configuration within the same package (and child packages) as RootConfiguration. Since SecurityConfig is in this package, it will be loaded with our existing setup and there is nothing more to do.

Had SecurityConfig not been loaded, we could have used an @Import(SecurityConfig.class) above the class definition of RootConfiguration or added SecurityConfig as one of the results for getRootConfigClasses().

Exploring the secured application

Start the server as we did in Running the insecuremvc application Now when you visit http://localhost:8080/sample/ you will be prompted with a login page that is automatically generated by Spring Security.

Authenticating to the secured application

Try entering an invalid username and password:

  • Username invalid

  • Password invalid

You should see an error message stating that authentication failed. Now try entering a valid username and password:

  • Username user

  • Password password

You should now see the page that we wanted to secure.

The reason we can successfully authenticate with Username user and Password password is because that is what we configured in our SecurityConfig.

Displaying the user name

Now that we have authenticated, let’s see how our application is displaying the username if the user is authenticated.

messages/src/main/resources/views/layout.html
<div th:if="${#httpServletRequest.remoteUser != null}">
    <p th:text="${#httpServletRequest.remoteUser}">
      sample_user
    </p>
</div>

In our samples we use Thymeleaf, but any view technology will work. Any technology can inspect the HttpServletRequest#getRemoteUser() to view the current user since Spring Security integrates with the Servlet API methods.

The Thymeleaf ensures the username is escaped to avoid XSS vulnerabilities Regardless of how an application renders user inputed values, it should ensure that the values are properly escaped.

Logging out

We can view the user name, but how are we able to log out? Below you can see how we are able to log out.

messages/src/main/resources/views/layout.html
<form th:action="@{/logout}" method="post">
    <input type="submit" value="Log out" />
</form>

In order to help protect against CSRF attacks, by default, Spring Security Java Configuration log out requires:

  • the HTTP method must be a POST

  • the CSRF token must be added to the request. Since we have used @EnableWebSecurity and are using Thymeleaf, the CSRF token is automatically added as a hidden input for you (view the source to see it).

If you were not using Spring MVC taglibs or Thymeleaf, you can access the CsrfToken on the ServletRequest using the attribute _csrf. You can find an example of including the CSRF token in a JSP within the Hello Spring Security Java Config.

Restart the application server and click the Log out button and see that the application logs you out successfully.

Conclusion

You should now know how to secure your application using Spring Security without using any XML. Next, we will see how to customize our login form.