Secured Navigator

Example code is available on github.com/vaadin-on-grails/spring-security-basics.

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.

package app.security

import com.vaadin.navigator.View
import org.springframework.security.authentication.InternalAuthenticationServiceException
import org.springframework.security.core.Authentication
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.context.SecurityContextHolder

class 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.

Step 3

Now we will create two views where one will be accesible only by "ADMIN" role.

And the second view, LoginView, that will public to everyone.

Step 4

Now we will create UI class that will initialize Navigator and ViewSecurity.

Step 5

Run application grails run-app and fill in username and password.

Login screen

Click on Login button and you will be authentificated and redirected to secured view.

Login screen

Last updated

Was this helpful?