我试图建立一个安全过滤链,并允许一些白色名单通过没有安全
这是我的依赖
implementation 'org.springframework.boot:spring-boot-starter-security:3.1.5'
字符串
我的过滤器
private static final String[] WHITE_LIST_URL = {"/ping/getEnvironment"};
public SecurityFilterChain securityFilterChain(HttpSecurity http) {
try {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL)
.permitAll()
.anyRequest()
.authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
} catch (Exception e) {
throw new IllegalStateException("Not able to build security filter chain", e);
}
}
型
我的测试
@Test
void getEnvironmentTest() throws Exception {
String rawResponse = mockMvc.perform(MockMvcRequestBuilders.get("/ping/getEnvironment"))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andReturn()
.getResponse()
.getContentAsString();
ObjectMapper objectMapper = new ObjectMapper();
PingResponse pingResponse = objectMapper.readValue(rawResponse, PingResponse.class);
Assertions.assertNotNull(pingResponse);
}
型
但这种方法失败了,
MockHttpServletResponse:
Status = 401
Error message = Unauthorized
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", WWW-Authenticate:"Basic realm="Realm"", X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Status
Expected :200
Actual :401
型
如你所见,我得到了401而不是200
1条答案
按热度按时间ltqd579y1#
我发现了。我缺少@Bean注解。在添加
@Bean
之后,我的测试按预期通过了这是我的安全过滤器chahin看起来像包括过滤器anotation。
字符串