Spring protection not calling my custom authentication filter when running JUnit tests

I am trying to implement basic stateless authentication with Spring Security by following this article

The problem I am facing is that my custom filter is not invoked by the infrastructure, even when my SecurityConfig looks almost the same as in the previous link (a bit simpler):

@Configuration @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("appAuthenticationProvider") private AuthenticationProvider authenticationProvider; @Autowired @Qualifier("appAuthenticationFilter") private AppAuthenticationFilter appAuthenticationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable(). sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests().anyRequest().authenticated() .and() .anonymous().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint()); http.addFilterBefore(appAuthenticationFilter, BasicAuthenticationFilter.class); } @Bean public AuthenticationEntryPoint unauthorizedEntryPoint() { return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } 

I do not post code for authenticationProvider and appAuthenticationFilter, since the former works fine (I can log in using the / endpoint entry), and the latter simply implements GenericFilterBean and is not even called.

Any help would be greatly appreciated!

+6
source share
2 answers

Well, I found a solution after I noticed that the filters are executed when the Spring Boot application is deployed, and they were not called only when the tests were run. Then I found this post:

https://spring.io/blog/2014/05/23/preview-spring-security-test-web-security

I forgot to configure my mock MVC to use filters. So finally, my test class for authentication looks like this:

 @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = GasApplication.class) @WebAppConfiguration public class LoginControllerTest { @Autowired private WebApplicationContext context; @Autowired @Qualifier("appAuthenticationFilter") private Filter appAuthenticationFilter; private MockMvc mockMvc; @Before public void init() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(context) .addFilter(appAuthenticationFilter, "/resource") .build(); } // Tests here... } 
+4
source

In order not to auto-install and configure the filter by hand, as in the previous answer, you can use SecurityMockMvcConfigurers.springSecurity ():

 MockMvcBuilders .webAppContextSetup(context) .apply(SecurityMockMvcConfigurers.springSecurity()) .build(); 
+1
source

Source: https://habr.com/ru/post/987994/


All Articles