【发布时间】:2020-01-28 14:20:14
【问题描述】:
在我的应用中,我在 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;
}
}
过滤器本身,负责通过调用外部授权服务器来验证访问令牌,定义为:
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);
}
}
我要做的是对定义为的控制器执行集成测试:
@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注释测试方法 - 设置
mockMvc和MockMvcBuilders(参见上面的setup()方法)和.apply(springSecurity())和没有它 - 用
@AutoConfigureMockMvc注释SomeControllerTest类(secure和addFilters参数都设置为false) - 用
@ContextConfiguration和@WebAppConfiguration注释SomeControllerTest类(我不知道它是否会改变什么)
这些方法都不会禁用身份验证。当我运行测试时,AuthenticationFilter 的 attemptAuthentication() 调用外部服务的方法仍然被调用,这是我不希望发生的。
【问题讨论】:
标签: java spring spring-security integration-testing