Vaadin21集成CustomAuthenticationProvider实现@RolesAllowed角色权限控制问题
问题根因
- 你在
SecurityConfiguration的configure(HttpSecurity http)方法中注释了super.configure(http)调用:VaadinWebSecurityConfigurerAdapter的父类配置逻辑包含了安全上下文持久化、视图权限拦截器注册、会话同步等核心逻辑,跳过该调用会导致你自定义AuthenticationProvider返回的带权限的认证Token没有被正确存入会话,后续请求读取到的就是未完成认证、权限为空的Token。 - 未开启JSR250注解支持:
@RolesAllowed属于JSR250规范的权限注解,需要显式开启才会被Spring Security识别校验。 - 角色前缀不匹配(潜在问题):Spring Security默认会给角色权限添加
ROLE_前缀,你当前返回的权限是admin、USER,和@RolesAllowed中配置的名称如果没有对应前缀会导致校验不通过。
修复步骤
步骤1:修正HttpSecurity配置
恢复configure(HttpSecurity http)方法开头的super.configure(http)调用,父类已经内置了Vaadin内部请求放行、CSRF忽略配置等逻辑,不需要手动重复实现,若有自定义需求可以在调用父类方法后修改配置:
@Override protected void configure(HttpSecurity http) throws Exception { // 必须先调用父类配置 super.configure(http); // 后续只保留你自定义的扩展逻辑即可 http.requestCache().requestCache(vaadinDefaultRequestCache); setLoginView(http, LoginView.class, LOGOUT_URL); viewAccessChecker.enable(); }
步骤2:开启JSR250注解支持
在SecurityConfiguration类上添加@EnableGlobalMethodSecurity注解开启权限注解扫描:
@EnableWebSecurity @Configuration // 开启JSR250注解支持,@RolesAllowed才会生效 @EnableGlobalMethodSecurity(jsr250Enabled = true) public class SecurityConfiguration extends VaadinWebSecurityConfigurerAdapter { // 原有代码保持不变 }
步骤3:(可选)关闭默认角色前缀
如果不需要Spring Security默认的ROLE_前缀,在SecurityConfiguration中添加如下Bean配置,保证你返回的权限名称和@RolesAllowed中配置的可以直接匹配:
@Bean public GrantedAuthorityDefaults grantedAuthorityDefaults() { // 配置空前缀,去掉默认的ROLE_前缀 return new GrantedAuthorityDefaults(""); }
验证
修改完成后重启项目,登录后可以通过以下代码确认当前认证信息的权限是否正确:
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); System.out.println(auth.getAuthorities());
确认权限正确后,标注@RolesAllowed的视图就可以正常触发角色校验了。
内容的提问来源于stack exchange,提问作者Süni∋r
相关产品推荐
相关产品推荐

