java - 在集成测试 RestController 时禁用或模拟 Spring Security 过滤器

标签 java spring spring-security integration-testing

在我的应用程序中,我在 WebSecurityConfigurerAdapter 扩展中添加了一个自定义过滤器:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final RequestMatcher PROTECTED_URLS = new AntPathRequestMatcher("/v1/**");

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
                .addFilterBefore(authenticationFilter(), AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .requestMatchers(PROTECTED_URLS)
                .authenticated()
            .and()
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable();
    }

    @Bean
    AuthenticationFilter authenticationFilter() throws Exception {
        final AuthenticationFilter filter = new AuthenticationFilter(PROTECTED_URLS);

        // filter setup...

        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }
}

过滤器本身负责通过调用外部授权服务器来验证访问 token ,定义如下:

public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    AuthenticationFilter(final RequestMatcher requiresAuth) {
        super(requiresAuth);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest,
                                                HttpServletResponse httpServletResponse)
        throws AuthenticationException, IOException, OAuth2Exception {
        try {
            // Get Authorization header.
            String token = httpServletRequest.getHeader(AUTHORIZATION);

            // Check if the token is valid by calling an external authorization server.
            // Returns some Authentication if successful.
        } catch (OAuth2Exception exception) {
            // Return 401
        } catch (Exception exception) {
            // All other errors are 500s
        }
    }

    @Override
    protected void successfulAuthentication(final HttpServletRequest request,
                                            final HttpServletResponse response,
                                            final FilterChain chain,
                                            final Authentication authResult)
        throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
        chain.doFilter(request, response);
    }
}

我想做的是在定义为的 Controller 上执行集成测试:

@RestController
@RequestMapping(value = "/v1", produces = "application/json")
public class SomeController {

    @Autowired
    private SomeService someService;

    @ResponseStatus(OK)
    @PostMapping(value = "/a/path")
    public SomeSuccessResponse pathHandlerMethod() {
        return someService.someServiceMethod();
    }
}

最后,我的测试设置如下:

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
@Import(SecurityConfig.class)
@ContextConfiguration
@WebAppConfiguration
public class SomeControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WebApplicationContext context;

    @MockBean
    private SomeService someService;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity()) // When I comment out this line I'm getting 404 errors instead.
            .build();
    }

    @Test
    @WithMockUser
    public void performIntegrationTest() throws Exception {
        mockMvc.perform(post("/v1/a/path")).andExpect(status().isOk());
    }
}

我希望在这种情况下关闭身份验证或以某种方式模拟身份验证 - 根本不应该调用 AuthenticationFilter 中的实际代码。为了实现这一点,在 SomeControllerTest 类中我尝试过:

  • 使用@WithMockUser注释测试方法
  • 使用 MockMvcBuilders 设置 mockMvc (请参阅上面的 setup() 方法)和 .apply(springSecurity()) 和没有它
  • 使用 @AutoConfigureMockMvc 注释 SomeControllerTest 类(将 secureaddFilters 参数设置为 )
  • 使用 @ContextConfiguration@WebAppConfiguration 注释 SomeControllerTest 类(我不知道它是否会改变任何内容)

这些方法都不会禁用身份验证。当我运行测试时,调用外部服务的 AuthenticationFilterattemptAuthentication() 方法仍然被调用,这是我不希望发生的情况。

最佳答案

禁用过滤器对于集成测试来说听起来很矛盾,恕我直言。您是否考虑过模拟过滤器?

创建

public class MockAuthenticationFilter implements Filter {
   // return mock data for different use cases. 
} 

然后在您的测试中注册此过滤器。

@Before
public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(context)
        .apply(springSecurity(new MockAuthenticationFilter()))
        .build();

}

这还允许您测试过滤器以一种或另一种方式运行的不同用例。

关于java - 在集成测试 RestController 时禁用或模拟 Spring Security 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59950812/

相关文章:

java - 长轮询 杀死服务器端的线程

java - 使用本地PC作为服务器

java - 用于 GWT 的静态 Google 地球 map

Spring Boot 验证注释不适用于 Kotlin

java - 将 Spring ModelAttribute 应用于所有使用特定参数类型的 Controller

java - Spring 3.1.1 RedirectUtils 相当于 Spring 3.2.4

java - 如何创建滚动背景?

java.lang.IllegalArgumentException "Can not set DAO field"与 Spring 4 & Hibernate 4

java - 如何将 Spring security 3 与 jboss 领域和用户角色集成?

grails - 拦截grails中的springsecurity行为