I am trying to security at api controller function itself so that if a particular user has specific role and allow that person to call that endpoint else response as 403.
@PostMapping("/user")
**@havingRole("ADMIN","LEADER")** <- my custom annotation.
public ResponseEntity<User> createUser(User user){
....
}
CodePudding user response:
Use annotation @PreAuthorize("hasRole('Role_Admin')")
CodePudding user response:
You can create your own annotation based on provided Spring functionality. Following your example:
@Inherited
@Retention(RUNTIME)
@Target({METHOD, TYPE})
@PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
public @interface AdminOrLeaderRoleRequired {
}
Now you can use it on individual methods:
@PostMapping("/user")
@AdminOrLeaderRoleRequired
public ResponseEntity<User> createUser(User user) {
...
}
Or in the class definition:
@RestController
@RequestMapping("/user")
@AdminOrLeaderRoleRequired
public class UserController {
...
}
Internal methods can overwrite it with their specific authorization rules.
