Vaadin 21 迁移到基于视图的访问控制 - RolesAllowed 不起作用

Vaadin 21 Migration to View-Based Access Control - RolesAllowed not working

这是 的后续问题。

我将我的 Vaadin 20 应用程序迁移到 21 以使用基于视图的访问控制。注释 @PermitAll@AnonymousAllowed 工作正常。但是,当我尝试使用 @RolesAllowed 将路由限制为特定用户角色时,我无法访问该站点(使用具有此角色的用户登录)。 是否需要一些特殊代码才能让 Vaadin 识别我的已验证用户的角色?

角色限制页面:

@Component
@Route(value = "admin", layout = MainLayout.class, absolute = true)
@RolesAllowed("admin")
@UIScope
public class AdminView ...

安全配置

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends VaadinWebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        setLoginView(http, LoginView.class, "/login");
    }
    
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/images/**");
    }
}

您传递给 @RolesAllowed 的角色区分大小写,并且应该与您在 Spring 安全性中拥有的角色相匹配。在您的情况下,您很可能想使用 @RolesAllowed({"ROLE_ADMIN"})。您可以在此处的文档中阅读更多内容 https://vaadin.com/docs/v21/flow/integrations/spring/view-based-access-control/#annotating-the-view-classes

经过大量的调试,我发现了问题,我实现的UserDetails.java中的getAuthorities()函数的实现是不正确的。具有一个角色的工作虚拟版本看起来像这样:

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of( new SimpleGrantedAuthority("ROLE_" + "admin"));
    }

重要的是在实际角色名称前添加 "ROLE_"。然后我可以在视图 class.

中使用 @RolesAllowed("admin")