Skip to content
Advertisement

Spring Test returning 401 for unsecured URLs

I am using Spring for MVC tests

Here is my test class

JavaScript

Here is the MVC config

JavaScript

Here is the security config

JavaScript

When I run my test it fails with the message:

JavaScript

I understand that it fails due to the fact that the url is protected with spring security, but when I run my application I can access that url even without being authenticated.

Am I doing something wrong?

Advertisement

Answer

I found the answer
Spring docs says that:

@WebMvcTest will auto-configure the Spring MVC infrastructure and limit scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver. Regular @Component beans will not be scanned when using this annotation.

And according to this issue in github:

https://github.com/spring-projects/spring-boot/issues/5476

The @WebMvcTest by default auto configure spring security if spring-security-test is present in the class path (which in my case is).

So since WebSecurityConfigurer classes aren’t picked, the default security was being auto configured, that is the motive I was receiving the 401 in url’s that was not secured in my security configuration. Spring security default auto configuration protects all url’s with basic authentication.

What I did to solve the problem was to annotate the class with @ContextConfiguration, and @MockBean like it is described in the documentation:

Often @WebMvcTest will be limited to a single controller and used in combination with @MockBean to provide mock implementations for required collaborators.

And here is the test class

JavaScript

Application, MvcConfig and SecurityConfig are all my configuration classes

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement