Is there a Spring counterpart for @RunAs?

JEE has an annotation @RunAs("role_name")that allows you to call application methods under a specific role.

Is there an analog @RunAsin Spring? If there are no equivalent annotations, which are other ways to call methods with some role?

+4
source share
3 answers

Configure spring RunAsManager , then annotate your method with @Secured("RUN_AS_<MY_ROLE>"), where <MY_ROLE>is the role you want the method to perform as.

The key here is the prefix RUN_AS. It starts the launch as logic to add a suffix role.

+1
source

Spring @PreAuthorize("hasRole('ROLE')") :

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

, ROLE SUPER_ADMIN, ADMIN.

+2

I also found a quick solution to add a user to the security context. Since I need this to call secure service methods in the Kafka listener class, this does not affect any authentication process in 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);
0
source

Source: https://habr.com/ru/post/1686352/


All Articles