Preview Spring Security Test: Web Security

Engineering | Rob Winch | May 23, 2014 | ...

[callout title=Updated March 31 2015]This blog is outdated and no longer maintained. Please refer to the Test Section of the reference documentation for updated documentation. [/callout]

In my previous blog we demonstrated how the new Spring Security testing support can ease testing method based security. In this blog we will explore how we can use the testing support with Spring MVC Test.

Setting Up MockMvc and Spring Security

In order to use Spring Security with Spring MVC Test it is necessary to add the Spring Security FilterChainProxy as a Filter. For example:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class CsrfShowcaseTests {

  @Autowired
  private WebApplicationContext context;

  @Autowired
  private Filter springSecurityFilterChain;

  private MockMvc mvc;

  @Before
  public void setup() {
      mvc = MockMvcBuilders
              .webAppContextSetup(context)
              .addFilters(springSecurityFilterChain)
              .build();
  }

  ...

[callout title=Source Code]You can find the complete source code for this blog series on github [/callout]

SecurityMockMvcRequestPostProcessors

Spring MVC Test provides a convenient interface called a RequestPostProcessor that can be used to modify a request. Spring Security provides a number of RequestPostProcessor implementations that make testing easier. In order to use Spring Security's RequestPostProcessor implementations ensure the following static import is used:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

Testing with CSRF Protection

When testing any non safe HTTP methods and using Spring Security's CSRF protection, you must be sure to include a valid CSRF Token in the request. Prior to the Spring Security testing support this was quite challenging. Now you can specify a valid CSRF token as a request parameter using the following:

mvc
    .perform(post("/").with(csrf()))

If you like you can include CSRF token in the header instead:

mvc
    .perform(post("/").with(csrf().asHeader()))

You can also test providing an invalid CSRF token using the following:

mvc
    .perform(post("/").with(csrf().useInvalidToken()))

Running a Test as a User

It is often desirable to run tests as a specific user. Prior to the Spring Security testing support this was challenging in web based tests since the SecurityContextHolder is modified by the SecurityContextRepositoryFilter.

There are now two simple ways of populating the user:

[callout title=NOTE] The testing support to run as a current user does not currently work when using Spring Security's stateless mode. This is being tracked at SEC-2593. [/callout]

Populating a Test User with a RequestPostProcessor

There are a number of options available to populate a test user. For example, the following will run as a user (which does not need to exist) with the username "user", the password "password", and the role "ROLE_USER":

mvc
    .perform(get("/").with(user("user")))

You can easily make customizations. For example, the following will run as a user (which does not need to exist) with the username "admin", the password "pass", and the roles "ROLE_USER" and "ROLE_ADMIN".

mvc
    .perform(get("/admin").with(user("admin").password("pass").roles("USER","ADMIN")))

If you have a custom UserDetails that you would like to use, you can easily specify that as well. For example, the following will use the specified UserDetails (which does not need to exist) to run with a UsernamePasswordAuthenticationToken that has a principal of the specified UserDetails:

mvc
    .perform(get("/").with(user(userDetails)))

If you want a custom Authentication (which does not need to exist) you can do so using the following:

mvc
    .perform(get("/").with(authentication(authentication)))

You can even customize the SecurityContext using the following:

mvc
    .perform(get("/").with(securityContext(securityContext)))

We can also ensure to run as a specific user for every request by using MockMvcBuilders's default request. For example, the following will run as a user (which does not need to exist) with the username "admin", the password "password", and the role "ROLE_ADMIN":

mvc = MockMvcBuilders
        .webAppContextSetup(context)
        .defaultRequest(get("/").with(user("user").roles("ADMIN")))
        .addFilters(springSecurityFilterChain)
        .build();

If you find you are using the same user in many of your tests, it is recommended to move the user to a method. For example, you can specify the following in your own class named CustomSecurityMockMvcRequestPostProcessors:

public static RequestPostProcessor rob() {
	return user("rob").roles("ADMIN");
}

Now you can perform a static import on SecurityMockMvcRequestPostProcessors and use that within your tests:

import static sample.CustomSecurityMockMvcRequestPostProcessors.*;

...

mvc
    .perform(get("/").with(rob()))

Populating a Test User with Annotations

As an alternative to using a RequestPostProcessor to create your user, you can use annotations described in my previous blog post. However, for this to work, you must specify a RequestPostProcessor runs the request with the user from the annotations as shown below:

mvc = MockMvcBuilders
        .webAppContextSetup(context)
        .addFilters(springSecurityFilterChain)
        .defaultRequest(get("/").with(testSecurityContext()))
        .build();

[callout title=NOTE] Do not forget to specify the WithSecurityContextTestExcecutionListener as described in the previous blog. [/callout]

Now you can run a test with any of the approaches described in Method Based Security Testing. For example, the following will run the test with the user with username "user", password "password", and role "ROLE_USER":

@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
  mvc
      .perform(get("/"))
      ...
}

Alternatively, the following will run the test with the user with username "user", password "password", and role "ROLE_ADMIN":

@Test
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithUser() throws Exception {
  mvc
      .perform(get("/"))
      ...
}

For additional information on how to use the annotations, refer to my previous blog.

Testing HTTP Basic Authentication

While it has always been possible to authenticate with HTTP Basic, it was a bit tedious to remember the header name, format, and encode the values. Now this can be done using Spring Security's httpBasic RequestPostProcessor. For example, the snippet below:

mvc
    .perform(get("/").with(httpBasic("user","password")))

will attempt to use HTTP Basic to authenticate a user with the username "user" and the password "password" by ensuring the following header is populated on the HTTP Request:

Authorization: Basic dXNlcjpwYXNzd29yZA==

SecurityMockMvcRequestBuilders

Spring MVC Test also provides a RequestBuilder interface that can be used to create the MockHttpServletRequest used in your test. Spring Security provides a few RequestBuilder implementations that can be used to make testing easier. In order to use Spring Security's RequestBuilder implementations ensure the following static import is used:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.*;

Testing Form Based Authentication

You can easily create a request to test a form based authentication using Spring Security's testing support. For example, the following will submit a POST to "/login" with the username "user", the password "password", and a valid CSRF token:

mvc
    .perform(formLogin())

It is easy to customize the request. For example, the following will submit a POST to "/auth" with the username "admin", the password "pass", and a valid CSRF token:

mvc
    .perform(formLogin("/auth").user("admin").password("pass"))

We can also customize the parameters names that the username and password are included on. For example, this is the above request modified to include the username on the HTTP parameter "u" and the password on the HTTP parameter "p".

mvc
    .perform(formLogin("/auth").user("a","admin").password("p","pass"))

Testing Logout

While fairly trivial using standard Spring MVC Test, you can use Spring Security's testing support to make testing log out easier. For example, the following will submit a POST to "/logout" with a valid CSRF token:

mvc
    .perform(logout())

You can also customize the URL to post to. For example, the snippet below will submit a POST to "/signout" with a valid CSRF token:

mvc
    .perform(logout("/signout"))

SecurityMockMvcResultMatchers

At times it is desirable to make various security related assertions about a request. To accommodate this need, Spring Security Test support implements Spring MVC Test's ResultMatcher interface. In order to use Spring Security's ResultMatcher implementations ensure the following static import is used:

import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;

Unauthenticated Assertion

At times it may be valuable to assert that there is no authenticated user associated with the result of a MockMvc invocation. For example, you might want to test submitting an invalid username and password and verify that no user is authenticated. You can easily do this with Spring Security's testing support using something like the following:

mvc
    .perform(formLogin().password("invalid"))
    .andExpect(unauthenticated());

Authenticated Assertion

It is often times that we must assert that an authenticated user exists. For example, we may want to verify that we authenticated successfully. We could verify that a form based login was successful with the following snippet of code:

mvc
    .perform(formLogin())
    .andExpect(authenticated());

If we wanted to assert the roles of the user, we could refine our previous code as shown below:

mvc
    .perform(formLogin().user("admin"))
    .andExpect(authenticated().withRoles("USER","ADMIN"));

Alternatively, we could verify the username:

mvc
    .perform(formLogin().user("admin"))
    .andExpect(authenticated().withUsername("admin"));

We can also combine the assertions:

mvc
    .perform(formLogin().user("admin").roles("USER","ADMIN"))
    .andExpect(authenticated().withUsername("admin"));

With HtmlUnit

We have now seen how Spring Security Test support can make testing with Spring MVC Test easier. In our next blog, we will explore how to use Spring Security Testing support with Spring Test MVC HtmlUnit.

[callout title=Feedback please!] If you have feedback on this blog series or the Spring Security Test support, I encourage you to reach out via JIRA, via the comments section, or ping me on twitter @rob_winch. Of course the best feedback comes in the form of contributions. [/callout]

Get the Spring newsletter

Thank you for your interest. Someone will get back to you shortly.

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

Get support

Tanzu Spring Runtime offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Learn more

Upcoming events

Check out all the upcoming events in the Spring community.

View all