如何配置MockMvc,让所有请求自动应用oauth2Login()请求后置处理器?
问题
给定以下Spring Security配置和测试代码:
安全配置类代码
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests( authorize -> authorize .requestMatchers("/api/**") .authenticated()) .oauth2ResourceServer(resourceServer -> resourceServer.jwt(withDefaults())) .oauth2Login(withDefaults()); return http.build(); }
控制器测试类代码
public class HelloControllerTests { @Autowired private MockMvc mockMvc; @Test public void shouldReturnWorld() throws Exception { this.mockMvc .perform(get("/api/hello").with(oauth2Login())) .andExpect(status().isOk()) .andExpect(content().string(containsString("Hello, World!"))); } @Test public void shouldReturnBob() throws Exception { this.mockMvc .perform(get("/api/hello").with(oauth2Login()).param("name", "bob")) .andExpect(status().isOk()) .andExpect(content().string(containsString("Hello, Bob"))); } }
目前存在的问题:大量测试用例中需要重复添加.with(oauth2Login()),希望配置MockMvc让所有请求自动包含这个认证逻辑,避免重复代码。
解决方案
有两种简洁的方式实现需求:
方法1:自定义MockMvc构建器,添加默认请求后置处理器
通过MockMvcBuilders.webAppContextSetup配置时,添加全局默认的请求处理器,自动为每个请求应用oauth2Login()认证:
@SpringBootTest @AutoConfigureMockMvc public class HelloControllerTests { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @BeforeEach void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .defaultRequest(get("/") .with(oauth2Login())) // 全局默认添加oauth2Login认证 .build(); } @Test public void shouldReturnWorld() throws Exception { this.mockMvc .perform(get("/api/hello")) // 无需再手动加with(oauth2Login()) .andExpect(status().isOk()) .andExpect(content().string(containsString("Hello, World!"))); } @Test public void shouldReturnBob() throws Exception { this.mockMvc .perform(get("/api/hello").param("name", "bob")) // 同样无需手动添加 .andExpect(status().isOk()) .andExpect(content().string(containsString("Hello, Bob"))); } }
方法2:使用MockMvcConfigurer自定义全局配置
创建一个自定义的MockMvcConfigurer,全局应用认证逻辑:
public class OAuth2LoginMockMvcConfigurer implements MockMvcConfigurer { @Override public void configureMockMvc(MockMvcBuilder builder) { builder.defaultRequest(get("/").with(oauth2Login())); } }
然后在测试类中注册这个配置器:
@SpringBootTest @AutoConfigureMockMvc public class HelloControllerTests { @Autowired private MockMvc mockMvc; @TestConfiguration static class TestConfig { @Bean public MockMvcConfigurer oAuth2LoginConfigurer() { return new OAuth2LoginMockMvcConfigurer(); } } // 测试方法无需修改,自动应用oauth2Login认证 @Test public void shouldReturnWorld() throws Exception { this.mockMvc .perform(get("/api/hello")) .andExpect(status().isOk()) .andExpect(content().string(containsString("Hello, World!"))); } }
内容的提问来源于stack exchange,提问作者udduu
相关产品推荐
相关产品推荐

