In this article we will show way how to create Vaadin application with secured views, where a view will be viewable by certain role.
Step 1
In ViewSecurity class we will store the mapping of a view to user roles. The class will be also responsible to verify whether a view is accesible by a user.
packageapp.securityimport com.vaadin.navigator.Viewimport org.springframework.security.authentication.InternalAuthenticationServiceExceptionimport org.springframework.security.core.Authenticationimport org.springframework.security.core.GrantedAuthorityimport org.springframework.security.core.context.SecurityContextHolderclass ViewSecurity { private static Map<Class<? extends View>, List<String>> views = [:] static add(Class<? extends View> view, List<String> roles) { views.put(view, roles) } static boolean isViewAccessible(View view) { List<String> roles = views.get(view.class) if (!roles) {// if roles is null, the access is public (not secured) return true } Authentication authentication = SecurityContextHolder.context.authentication if (!authentication) { throw new InternalAuthenticationServiceException('No authentication found in the context.') } List<GrantedAuthority> authorities = authentication.authorities for (String role : roles) { boolean isRoleAssigned = role in authorities*.authority if (isRoleAssigned) { return true } } return false }}
Step 2
We need to hook at event when a view changes, so we can verify whether a user is able to access a view.