Spring security hasAnyRole 和不同权限的不同流程

Spring security hasAnyRole and different flows for different permissions

在我的 Spring 引导应用程序中,我有一个具有以下方法的 REST 控制器:

@PreAuthorize("hasAnyRole('PERMISSION_UPDATE_OWN_COMMENT', 'PERMISSION_UPDATE_ANY_COMMENT')")
@RequestMapping(value = "/update", method = RequestMethod.POST)
public CommentResponse updateComment(@AuthenticationPrincipal User user, @Valid @RequestBody UpdateCommentRequest commentRequest) {
    Comment comment = commentService.updateComment(commentRequest.getCommentId(), commentRequest.getTitle(), commentRequest.getContent(), user);
    return new CommentResponse(comment);
}

只有 PERMISSION_UPDATE_OWN_COMMENTPERMISSION_UPDATE_ANY_COMMENT 的用户才可以使用此端点。

在此方法中,我需要创建两个不同的流 - 一个用于具有 PERMISSION_UPDATE_OWN_COMMENT 权限的用户,另一个用于具有 PERMISSION_UPDATE_ANY_COMMENT 权限的用户。

所以我的问题是 - Spring 安全的最佳实践是什么,以便在单个方法内实现这些不同的逻辑流?

我是否应该在 updateComment 方法内部验证用户是否具有一个或另一个权限并根据此条件实现我的逻辑?

最简单的方法是在控制器中执行 updateComment 函数中的逻辑。因为,您可以轻松地从操作参数中获取 SecurityContextHolderAwareRequestWrapper 的实例来查找角色。

最佳做法是将您的逻辑放在服务中。这将使您的生活更容易在 RESTFul APIs.

等其他地方重用逻辑

因此您可以使用以下代码或类似的代码来检查服务中的角色。

Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
boolean authorized = authorities.contains(new SimpleGrantedAuthority("PERMISSION_UPDATE_OWN_COMMENT"));

(编辑了更多信息)

可用于检查的完整功能roles

protected boolean roleExist(String role) {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    for (GrantedAuthority auth : authentication.getAuthorities()) {
        if (role.equals(auth.getAuthority()))
            return true;
    }
    return false;
}