Is there a Spring analog for @RunAs?

Viewed 1682

In JEE there is @RunAs("role_name") annotation, that allows to invoke application methods under a particular role.

Is there a @RunAs analog in Spring? If there is no equivalent annotations, which are other ways to invoke methods with some role?

3 Answers

With Spring Security, you can use @PreAuthorize("hasRole('ROLE')") as:

    @PreAuthorize("hasRole('ROLE_SUPER_ADMIN') or hasRole('ROLE_ADMIN')")
    public ResponseEntity<UserResponse> getAllUserByRole(...) {
    }

What it is saying is, this particular method can be invoked by only user with ROLE either SUPER_ADMIN or ADMIN.

Set up the spring RunAsManager then annotate your method with @Secured("RUN_AS_<MY_ROLE>"), where <MY_ROLE> is the role you wish to execute the method as.

The key here is the prefix RUN_AS. It triggers the run as logic to add the suffixed role.

I also found a quick solution of adding a custom user into security context. Since I need this for invoking secured service methods in Kafka listener class, that is not affected by any authentication process by itself.

User user = new User("SYSTEM", "SYSTEM", "SYSTEM");
UserDetailsImpl userDetails = new UserDetailsImpl(user, 
Arrays.asList(<YOUR_ROLE_HERE>)); 
// UserDetailsImpl - class that implements 
// org.springframework.security.core.userdetails.UserDetails
UsernamePasswordAuthenticationToken token = 
    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(token);
Related