可通过为api端点配置异常处理器的认证端点,实现防止跳转登录的效果
@Bean
SecurityFilterChain oauth2SecurityFilterChain(
HttpSecurity http
) throws Exception {
// 请求api时,如果发生认证异常,返回401响应而不跳转登录
http.exceptionHandling(
handling -> handling.defaultAuthenticationEntryPointFor(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
AntPathRequestMatcher.antMatcher("/api/**")
)
);
...
}