You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vaadin24/SpringBoot3升级后API认证失败跳转登录而非返回401求助

解决Vaadin 24/Spring Boot 3下API认证失败重定向至登录页的问题

问题分析

升级到Vaadin 24和Spring Boot 3后,API请求认证/授权失败时被重定向到Vaadin登录页而非返回401,核心原因有两点:

  1. Spring Boot 3依赖的Spring Security 6已弃用WebSecurityConfigurerAdapter,旧版配置方式不再完全生效,导致Rest API的安全规则未被优先执行。
  2. Vaadin 24的VaadinWebSecurity默认会拦截所有请求路径,若未明确排除/api/**,会覆盖Rest API的安全处理逻辑。

解决方案

1. 重构Rest API安全配置(适配Spring Security 6新规范)

替换旧的继承WebSecurityConfigurerAdapter的方式,改用SecurityFilterChain Bean配置,并确保优先级高于Vaadin配置:

// Config for the REST API
@Configuration
@Order(1)
public static class MyRestApiSecurityConfig {

    @Bean
    public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/api/**") // 仅匹配/api路径下的所有请求
            .cors(cors -> cors.disable())
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .anyRequest().hasAuthority(AppRoles.API)
            )
            .httpBasic(basic -> basic
                .authenticationEntryPoint(new RestAuthenticationEntryPoint())
            );
        return http.build();
    }
}

2. 调整Vaadin安全配置,排除API路径

修改MyUIWebSecurity,明确让Vaadin不处理/api/**路径,避免干扰Rest API的安全逻辑:

// Config for Vaadin
@Configuration
@Order(2)
public static class MyUIWebSecurity extends VaadinWebSecurity {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 排除/api路径,让Vaadin安全过滤器仅处理非API请求
        http.requestMatcher(new NegatedRequestMatcher(new AntPathRequestMatcher("/api/**")));
        super.configure(http);
        setLoginView(http, LoginView.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        // 忽略/api路径的资源检查,直接放行到Rest API配置
        web.ignoring().requestMatchers("/api/**");
    }
}

3. 保留原有的RestAuthenticationEntryPoint

原有的RestAuthenticationEntryPoint无需修改,它会在API认证失败时正确返回401状态码:

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

关键说明

  • @Order(1)确保Rest API的安全过滤器链优先执行,匹配到/api/**的请求不会进入Vaadin的过滤器链。
  • NegatedRequestMatcher用于排除API路径,让Vaadin仅处理UI相关请求。
  • Spring Security 6要求使用SecurityFilterChain Bean替代旧的WebSecurityConfigurerAdapter,这是升级后的核心配置变化。

内容的提问来源于stack exchange,提问作者BKDev101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:44:55