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

偶尔善良 提交于 2019-12-05 04:55:11

Ok, I found the solution after I noticed that the filters were being executed when deploying the Spring Boot app, and they were not being called only when running tests. 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 the authentication looks as follows:

@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...
}

To not autowire and set up your filter by hands as in the previous answer, you can use SecurityMockMvcConfigurers.springSecurity():

MockMvcBuilders
.webAppContextSetup(context)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!