Nabil
Nabil

Reputation: 1811

Role and permission custom Model

I have a custom Model of Autorization that i want to represent with spring security :

I have the concpt of roles and permissions :

@Entity
public class User
...............
@ManyToMany
@Column
private Set<Role> roles;


@ManyToMany
@Column
private Set<Permission> permissions;
  }

In my custom UserdetailsService i have a clean way to load the roles but i on't find any way and any componenent in spring-security related to the permissions :

public class BELUserDetailService implements UserDetailsService {

 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
 User connectedUser = userRepositoy.findUserByUsername(username);

     Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    for (Role r :connectedUser.getRoles()) {
        authorities.add(new SimpleGrantedAuthority(r.getRoleAWB().name()));
    }


    BELUserDetails belUserDetails = new BELUserDetails(connectedUser.getIdUser(), authorities);
.....
....
    }

}

My roles are :

ADMIN NORMAL USER TRANSACTION USER

My Permissions are : VALIDATE_TRANSATION INIT_TRANSACTION

And the functional use case is if you want Validate a Transaction you have to have the ROLE TRANSACTION USER and the permission VALIDATE_TRANSACTION.

hasRole("ROLE_TRANSACTION_USER") and hasPermission("VALIDATE_TRANSACTION")

Another important case is that i want in the future use PermissionEvaluator to put some limits when trying to validate a transaction if the user has the Role "ROLE_TRANSACTION_USER" and the permission VALIDATE_TRANSACTION , he must also have a Amountlimit greater than the amount of the transaction and this functionality is very cool with PermissionEvaluator

That's why i need to implements both Role and permission Concepts

How i will add my permission to the standard flow of spring-security .

Thanks in advance .

Upvotes: 0

Views: 700

Answers (1)

Maksym Demidas
Maksym Demidas

Reputation: 7817

By default you have only authorities in Spring Security. Just add all your roles and permissions into authorities collection. Then you can do:

hasRole("ROLE_TRANSACTION_USER") and hasRole("VALIDATE_TRANSACTION")

In most cases mixing the two is not a problem.

You have permissions in Spring Security ACL module, but you need ACL only if you want to have different security rules per domain object.

EDIT. I think the most easy way to do some additional security checks is to use SpEL. Example:

@PreAuthorize("hasRole('ROLE_TRANSACTION_USER') 
     and hasRole('VALIDATE_TRANSACTION') 
     and @amountValidatorServiceBean.isAmountValidForCurrentUser(#amount)")
public void doTransaction(Integer amount, ...)

Upvotes: 1

Related Questions