Using Spring Security 4.x Testing Features

Spring Framework 4.x Security added some great features for testing. We’re going to see some of them in action here, but two points before we begin. 1) The features we’re covering today were mostly released in Spring Framework 4, not to be confused with some of the new testing features coming in Spring Boot 1.4. 2) Everything we see today is covered in the Spring Security Reference, so you’ll definitely want to add that to your reading list.

We added a new Administration Area in our NixMash Spring app which is restricted to Administrator Role users. We’re going to test security on the /admin path and look at some Spring 4 Security enhancements along the way.

The @Setup

Establishing Spring Security Context is now cleaner with a springSecurity() MockMvc Configurer. SpringSecurity() adds the Spring Bean named “springSecurityFilterChain” as a Security Servlet Filter.

Using a Custom Principal

Spring Security’s new @WithMockUser annotation makes user testing easy. It also supports @WithAnonymousUser. @WithMockUser expects the standard principal returned from UserDetailsService. In NixMash Spring we use a custom principal that is returned from UserDetailsService, so using @WithMockUser would throw object casting exceptions if we used it. Fortunately there’s the new @WithUserDetails annotation which supports custom principals.

We’re going to see @WithUserDetails in a minute, but first here is a @WithAdminUserDetails custom annotation we created to streamline the use of assigning the Admin User to our test methods.

Here is our Interface class, showing the use of @WithUserDetails in full.

Non-Admin Access @Tests

Now we’ll use a non-Admin user. We specify our custom UserDetailsService bean name in @WithUserDetails. The username defaults to “user.”

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.