How to make components enabled based on Spring Security GrantedAuthority?

Hi Vaadin’s, I have successfully secured my application with Spring Security and view-based access control as described in Vaadins documentation. Now I need to make some components available or not depending on the user’s role. To be precise: I want to show a DIV only to users of role “admin”.

  • May I use Security annotation on components, too? (Probably not - as the documentation states “views”)
  • Using the AuthenticationContext and getting the user, how can I get the granted authorities from this user?
  • Maybe, my approach is not good, any other advice on how to render components depending on roles?

Thank you.

You can’t use security annotations for non-Route components. Check https://www.baeldung.com/spring-security-check-user-role for some options.

You should always also check that the current user has the correct authority to execute server-side operations (like if a non-admin tries to execute a method that deletes a user, throw an exception)

Thanks Olli. So no Component-Annotation available. Will use raw Spring Security and also use method annotations. Good advice.

You actually can use security annotations for non-route components, but it requires a bit of infrastructure

https://github.com/sunshower-io/groovv-core/blob/main/groovv/src/main/java/io/groovv/app/ui/views/admin/components/UserRegistrationListProvider.java

(i.e. it’s not supported out of the box, but it is possible (and pretty cool once you get it working))

basically you traverse the component tree before its sent to the client and filter out any components that aren’t visible to the current role

Nice one. Thanks!