我有一个正在运行的 Spring Boot 应用程序(WEB、安全),它可以通过
@Controller
很好地提供网页服务。我想向其中添加一些额外的 API 端点。所以我所做的就是构建一个单独的 SecurityFilterChain
和 RestController
。
SecurityFilterChain
:
@Bean
@Order(1)
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
return http
.securityMatchers(matchers -> matchers
.requestMatchers("/api/**"))
.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll())
.csrf(CsrfConfigurer::disable)
.cors(CorsConfigurer::disable)
.build();
}
apiFilterChain 放置在 mvcFilterChain 的前面,因此后面的过滤器不会以某种方式干扰。
RestController
:
// @Controller /* This annotation works */
@RestController /* This annotation won't work */
@RequestMapping("/api")
public class ApiRestController {
@GetMapping("/test")
public ResponseEntity<?> getChallenge() {
return new ResponseEntity<>("aloha", HttpStatus.OK);
}
}
不幸的是,当我尝试通过 Postman
https://localhost:8081/api/test
发送 GET 请求时,我得到的只是 404 Not Found
。
令人惊讶的是,当我将
@RestController
替换为 @Controller
时,一切正常。这让我得出两个可能的假设:
@Controller
注释的端点,当没有端点时,mvcFilterChain将按预期拒绝请求。有人知道如何解决这个问题吗?
非常感谢提前
尝试在安全配置类上添加
@EnableWebSecurity
注释。这应该可以解决您的问题。