javaauthenticationspring-securityvaadin-flowvaadin21

Vaadin 21 View Roles


I want to rewrite my Vaadin application to Vaadin 21. With the Vaadin starter builder (https://vaadin.com/start) I created a simple app. Currently my main struggle is to apply my simple CustomAuthenticationProvider to the Security manager to able to use the @RolesAllowed({ "user", "admin","USER"}) annotation.

Main problem that my AuthToken is generated somewhere else... Its generate somewhere an empty Granted Authrities and ignore my custom AuthProvider code.

Question: How to nicely handle role based access control?

Where I can use this annotation correctly:

@RolesAllowed({ "user", "admin","USER"})
public class ProfileView extends VerticalLayout {

Console after login:

UsernamePasswordAuthenticationToken [Principal=c.farkas, Credentials=[PROTECTED], Authenticated=false, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=DDE103F559B2F64B917753636B800564], Granted Authorities=[]]
xxx[USERcica, admin, USER]
??UsernamePasswordAuthenticationToken [Principal=c.farkas, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[USERcica, admin, USER]]

SecurityConfiguration.java

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends VaadinWebSecurityConfigurerAdapter {

    @Autowired
    private RequestUtil requestUtil;

    @Autowired
    private VaadinDefaultRequestCache vaadinDefaultRequestCache;
    
    @Autowired
    private ViewAccessChecker viewAccessChecker;
    
    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;



    public static final String LOGOUT_URL = "/";

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//      super.configure(http);

        http.csrf().ignoringRequestMatchers(requestUtil::isFrameworkInternalRequest);
        // nor with endpoints
        http.csrf().ignoringRequestMatchers(requestUtil::isEndpointRequest);

        // Ensure automated requests to e.g. closing push channels, service
        // workers,
        // endpoints are not counted as valid targets to redirect user to on
        // login
        http.requestCache().requestCache(vaadinDefaultRequestCache);

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlRegistry = http
                .authorizeRequests();
        // Vaadin internal requests must always be allowed to allow public Flow
        // pages
        // and/or login page implemented using Flow.
        urlRegistry.requestMatchers(requestUtil::isFrameworkInternalRequest).permitAll();
        // Public endpoints are OK to access
        urlRegistry.requestMatchers(requestUtil::isAnonymousEndpoint).permitAll();
        // Public routes are OK to access
        urlRegistry.requestMatchers(requestUtil::isAnonymousRoute).permitAll();
        urlRegistry.requestMatchers(getDefaultHttpSecurityPermitMatcher()).permitAll();

        // all other requests require authentication
        urlRegistry.anyRequest().authenticated();

        // Enable view access control
        viewAccessChecker.enable();

        setLoginView(http, LoginView.class, LOGOUT_URL);
    }
    

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Custom authentication provider - Order 1
        auth.authenticationProvider(customAuthenticationProvider);

        // Built-in authentication provider - Order 2
    /*  auth.inMemoryAuthentication().withUser("admin").password("{noop}admin@password")
                // {noop} makes sure that the password encoder doesn't do anything
                .roles("ADMIN") // Role of the user
                .and().withUser("user").password("{noop}user@password").credentialsExpired(true).accountExpired(true)
                .accountLocked(true).roles("USER");*/
    }

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

CustomAuthenticationProvider.java

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        System.out.println(authentication);

        try {
//          LdapContext ldapContext = 
            ActiveDirectory.getConnection(username, password);
            List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();

            authorityList.add(new SimpleGrantedAuthority("USER" + "cica"));

            authorityList.add(new SimpleGrantedAuthority("admin"));
            authorityList.add(new SimpleGrantedAuthority("USER"));
            
            System.out.println("xxx"+authorityList.toString());

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    username, password, authorityList);

            System.out.println("??" + usernamePasswordAuthenticationToken);

            String id = VaadinSession.getCurrent() != null ? VaadinSession.getCurrent().getSession().getId() : "";
            return usernamePasswordAuthenticationToken;
        } catch (NamingException e) {
//          e.printStackTrace();
//          throw new CortexException("Authentication failed");
            throw new BadCredentialsException("Authentication failed");
        }

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }
}

Solution

  • You must add the ROLE_ prefix to tell Spring Security that the GrantedAuthority is of type role.

    authorityList.add(new SimpleGrantedAuthority("ROLE_USER" + "cica"));
    authorityList.add(new SimpleGrantedAuthority("ROLE_admin"));
    authorityList.add(new SimpleGrantedAuthority("ROLE_USER"));