Software Development, Spring, Spring Boot

Spring Boot Security Tests With PreAuth And WithMockUser

When we implement authorization in Spring Boot with Spring Security, for instance, using the PreAuth annotation, we should never skip automated tests for it. We could use the @PreAuth, among other annotations, to control authenticated users’ access to some methods or even endpoints. However, the ease of usage of these annotations could also mean ease of change. With just a handful of string properties to affect their behaviors, we could inadvertently allow access to restricted resources or operations when we change something. Therefore, we should create tests for codes that use these annotations for authorization.

Spring Boot And Spring Security

Let us say we have a working Spring Boot application with authentication and authorization features. Some of our codes could look like the following. We have a controller with two methods showing all or searching for permissions belonging to a particular tenant. To access the permission data, the current user has to have either permission – find_permission or view_permission.

Using the PreAuth and MockWitUser Annotations

We craft integration tests when we create automated tests for Spring Boot authorization (e.g., via PreAuth) that use Spring Security. These tests require interaction with Spring Boot and Spring Security components at runtime. Therefore, we need to load some codes in the Spring context.

The integration tests for our Permission REST controller may look something like the following.

Note that we are using another annotation – @WithMockUser – to mock a logged-in user with roles or authorities we want to test. For example, a pair of methods try for a user with the view_permission permission and without it. Spring Security has other annotations for a similar purpose. However, for this post, we stick with @WithMockUser.

To use these annotations, we need to use the following Maven dependency along with spring-boot-starter-test, and spring-security to mention a few.

The codes herein are part of the Headstart Framework we are developing using Spring Boot 2.5.5.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like