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

Vaadin视图Spring Security注解失效问题求助

Vaadin视图Spring Security注解失效的排查与解决

问题根源

  1. 方法级安全未启用:@DenyAll属于JSR-250安全注解,默认Spring Security不开启这类注解的解析逻辑,导致注解直接被忽略
  2. 安全配置不兼容Vaadin:普通Spring Security的authorizeRequests规则无法适配Vaadin的请求处理机制,Vaadin需要专用的安全拦截逻辑才能识别视图上的安全注解
  3. 路径冲突风险:Vaadin视图的@Route("/")与Thymeleaf的根路径重叠,可能导致安全规则未正确作用到Vaadin请求

排查方向

  • 检查依赖完整性:确认项目中引入了Vaadin Spring Security相关依赖(如com.vaadin:vaadin-spring-security),没有则补充
  • 验证方法级安全开关:查看安全配置类是否开启了JSR-250注解支持
  • 核对路径匹配:确认Vaadin servlet映射的/vdn/与视图@Route路径无冲突,确保安全规则覆盖到Vaadin请求

解决方案

1. 启用方法级安全

在WebSecurityConfig类上添加@EnableGlobalMethodSecurity注解,明确开启JSR-250、PrePost等安全注解的解析:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends VaadinWebSecurity {
    // 现有代码保留
}

2. 改用Vaadin专用安全配置

继承VaadinWebSecurity类,让Vaadin处理自身路径的安全拦截,同时保留Thymeleaf的Spring Security规则:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends VaadinWebSecurity {

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .dataSource(dataSource)
                .usersByUsernameQuery("select username, password, enabled from person where username=?")
                .authoritiesByUsernameQuery("select username, role from person where username=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 让Vaadin处理自身路径的安全逻辑
        super.configure(http);
        
        // 配置Thymeleaf对应的Spring MVC路径安全规则
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers("/").authenticated()
                .anyRequest().permitAll()
        );
        
        // 忽略Vaadin路径的CSRF校验(适配Vaadin的请求机制)
        http.csrf(csrf -> csrf.ignoringRequestMatchers("/vdn/**"));
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        // 放行Vaadin静态资源,避免被安全拦截
        web.ignoring().requestMatchers("/VAADIN/**", "/vdn/**/VAADIN/**");
    }
}

3. 调整Vaadin视图路径(可选)

由于Vaadin servlet映射到/vdn/,建议修改视图的@Route路径,避免与Thymeleaf根路径冲突:

@Route("/vdn/")
@StyleSheet("context://../vaadin.css")
@DenyAll
public class MainView extends AppLayout {
    // 视图代码保留
}

4. 验证配置生效

重启项目后测试:

  • 访问Vaadin视图,@DenyAll生效的话,无论是否登录都无法访问该页面
  • 测试@PreAuthorize("hasRole('ADMIN')")等其他安全注解,确认权限控制正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:31:02