Best way to implement authorization per group in spring security

Viewed 1230

I'm trying to find the best approach to authorize certain actions for a user based on the role they have in a group.
For instance Peter has admin role in group A so he can kick members in group A and member role in group B so he can only read content from group B.
this is what model of user group relationship looks like.
Is there a better way to implement authorization than loading group role in UserDetails like this:

(for (GroupUser groupuser: user.getGroupUsers()) {
   authorities.add(new SimpleGrantedAuthority('Group_'+groupuser.getId().getGroupId()+'_'+groupuser.getRole()));} 
1 Answers

This is the ABAC permission model which the security decision is not only determined by the user 's information , but also determined from the state/attribute of the protected resource too.

In term of spring security , it is best implemented using @PreAuthorize / @PostAuthorize / @PostFilter which allow you to use a SpEL expression to declaratively define the security logic which is an expression that will finally evaluate to true/false. In SpEL , you can access the input parameter and the return object of the method which performs that use-case that you want to apply security or even refer to a spring bean to call its method to do the evaluation.

For example, you could do something like :

@PreAuthorize("@authzService.isAllowToKickMember(principal , #userToKick)")
public void kickMemeber(User userToKick){
    
}


@Service
public class AuthzService{

    public boolean isAllowToKickMember(User currentUser , User userToKick){
        //check if current user can kick a given user
    }
}

For pointers , please check out this.

Related