Tapan
Tapan

Reputation: 187

Roles and Permission at method level Spring boot

I need to have authorization at the method level so that the users with proper permissions only can access it. The method will contain a token as a parameter. I need to make an API call passing the token and get the user email id. Once I have the email id, I need to fetch the user's roles & permissions from the database. Then I invoke the method if the user have appropriate roles else return a 403 error.

Is there a way to get this done in spring boot? I will have multiple methods behind authorization and would like to have some kind of annotation at method level.

Thanks.

Upvotes: 0

Views: 3889

Answers (2)

java dev
java dev

Reputation: 372

You can use @PreAuthorize with more flex as:-

@PreAuthorize("@securityService.hasPermission({'PERMISSION_1'})")

and service:-

@Component("securityService")
public class SecurityService {
    public boolean hasPermission(PermissionEnum... permissions) {

        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
                .getAuthorities();

        for (PermissionEnum permission : permissions) {
            if (authorities.contains(new SimpleGrantedAuthority(permission.toString))) {
                return true;
            }
        }
        return false;
    }
}

You can make it as you want.
For more

Upvotes: 0

Roie Beck
Roie Beck

Reputation: 1175

@PreAuthorize annotation is what you want

Please read the following link for spring method level authorization baeldung method authorization

you will also need to undestand SPEL(Spring Expression Language) as this is what the PreAuthorize method gets as parameter , link can be found here

please note that spring uses the SecurityContext to get the user data(Role etc..), meaning that the user already passed the login(authentication) stage and has SecurityContext loaded for said user

Example:

//other annotations 
@PreAuthorize("hasRole('ROLE_VIEWER')") // hasRole('ROLE_VIEWER') -> this is SPEL
public ResponseEntity<String> methodName() {
 //method
}   

Upvotes: 1

Related Questions