Home > Software design >  Vaadin 21 Migration to View-Based Access Control - RolesAllowed not working
Vaadin 21 Migration to View-Based Access Control - RolesAllowed not working

Time:10-07

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

CodePudding user response:

The roles you pass into @RolesAllowed are case-sensitive and should match the roles you have in Spring Security. Most likely in your case, you want to use @RolesAllowed({"ROLE_ADMIN"}). You can read more in the docs here https://vaadin.com/docs/v21/flow/integrations/spring/view-based-access-control/#annotating-the-view-classes

CodePudding user response:

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.

  • Related