spring security: what's the best practice for include value in permission?

242 views Asked by At

In spring security, or RBAC, the Authority is described as a string, such as "download-file" means user can download file. If I need to limit user maximum daily download times and assign different values to different user, means the Authority contains dynamic values, how can I do this in spring security?

2

There are 2 answers

1
Rob Winch On

As you are alluding to there is a difference between authorities (i.e. roles) and permissions. Authorities tend to broadly apply for an application and have no state while permissions tend to be on specific objects and contain state.

This seems more like a domain problem than a permissions problem. Putting the logic into security feels a bit like having a form that must contain a valid email and checking the email format in security. I'd consider moving the logic outside of the security code.

If you really want to do this with Spring Security, I'd use a custom Bean that performs the check:

@Component
public class Download {

    public boolean isAlowedForUser(Authentication authentication) {
       // ...
       return result;
    }

    public boolean isAllowedForCurrentUser() {
       return isAllowedForUser(SecurityContextHolder.getContext().getAuthentiation());
    }
}

Then you can autowire the Bean into your code and check the permission by invoking the code. If you prefer, you can also integrate into Spring Security's method security to perform the checks. To enable it you need to specify @EnableGlobalMethodSecurity(prePostEnabled = true) at the top of one of your configuration classes. Then you can use something like this on a Spring managed Bean:

@PreAuthorize("@download.isAllowedForCurrentUser()")
public void downloadFile(String fileName) {
0
Ashish On

Please refer this link Spring Boot : Custom Role - Permission Authorization using SpEL

You can add new permission , like "DOWNLOAD_FILE" and authenticate if the current user has that permission using -

@PreAuthorize("hasPermission('DOWNLOAD_FILE')")

You can also limit access for Roles as well

@PreAuthorize("hasRole('ADMIN') and hasPermission('DOWNLOAD_FILE')")