How to restrict user functionality

Cayman :

I need to restrict edtiting functionality in my Vaadin 12 app basing on user assigned roles

Currently we have page level security, i.e user can see only pages basing on assigned roles, like @Secured(Role.VIEW_PAGE)

User must see view button when view role assigned and see edit button when edit role assigned.

kscherrer :

You can use this method for this, which accepts one Role and looks if the users authorities contain this Role. It basically does the same as SecurityUtils.isAccessGranted(securedClass) only it looks for a specific role and not the roles defined in the @Secured annotation of a view.

public static boolean userHasRole(Role role){ // your own Role class/enum
    Authentication userAuthentication = SecurityContextHolder.getContext().getAuthentication();
    List<String> allowedRoles = Arrays.asList(role.name());
    return userAuthentication.getAuthorities().stream().map(GrantedAuthority::getAuthority)
                .anyMatch(allowedRoles::contains);
}

A good place to define this method is the already mentioned SecurityUtils class if you already have it. If not, now is a good time to create one ;).

You can now call the method like this in your view:

if(SecurityUtils.userHasRole(Role.EDIT_PAGE)){
    add(new Button("Edit"));
} else {
    add(new Button("View"));
}

If you wish, you can of course change this method to accept a list of roles instead of only one.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=160079&siteId=1