spring-bootspring-securityvaadinvaadin21

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


This is a follow up question to this question.

I migrated my Vaadin 20 application to 21 to use view-based access control. The Annotations @PermitAll and @AnonymousAllowed are working fine. However when I try to restrict a route to a specific user role with @RolesAllowed I can't get access to this site (being logged in with a user who has this role). Is there some special code required to get Vaadin to recognize the roles of my authenticated user?

Role restricted page:

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

SecurityConfig

@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/**");
    }
}

Solution

  • After a lot of debugging, I found the problem, the implementation of the getAuthorities() Function in my implementation of UserDetails.java was incorrect. A working dummy version with one role looks something like this:

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

    Important was to add "ROLE_" in front of the actual role name. Then I can use @RolesAllowed("admin") in the view class.