If you want to authorize with a little complicated logic in Spring Security method authorization, you can call the method of any bean.
By the way, if you want to add custom authentication correctly, implementing PermissionEvaluator is probably a legitimate approach. This article was easy to understand and detailed about the implementation of PermissionEvaluator. This is recommended if you want to add a general-purpose Evaluator for extension framework development. https://www.codeflow.site/ja/article/spring-security-create-new-custom-security-expression
This time, the procedure is that you can write in a slightly easier way.
Controller.java
@PreAuthorize("@customPreAuthorizer.belongGroup(#groupId, authentication.principal)")
@RequestMapping("/group/{groupId}/list")
public String list(Model model, @PathVariable("groupId") Long groupId) {
}
CustomPreAuthorizer.java
@Component
public class CustomPreAuthorizer {
public boolean belongGroup(Long groupId, UserDetails userDetails) {
//Implement your own authorization here. Returns true if allowed to run.
return true;
}
}
By adding @ at the beginning of the bean name in the expression of PreAuthorize, you can refer to the bean registered as a component.
@customPreAuthorizer
User information of the authenticated user can be passed as an argument with ʻauthentication.principal`.
If the description passed to the argument in PreAuthorize is redundant, the same thing can be obtained by calling SecurityContext in the method, so it can be retrieved in the method.
CustomPreAuthorizer.java
@Component
public class CustomPreAuthorizer {
public boolean belongGroup(Long groupId) {
var userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return true;
}
}
After that, if you extend User Details and have the necessary information at login, you can implement and provide the extended original authorization.
Recommended Posts