【问题标题】:Spring security hasAnyRole and different flows for different permissionsSpring security hasAnyRole和不同权限的不同流
【发布时间】:2015-06-06 12:35:47
【问题描述】:

在我的 Spring Boot 应用程序中,我有一个带有以下方法的 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 方法内部验证用户是否拥有一个或另一个权限并基于此条件实现我的逻辑?

【问题讨论】:

标签: spring spring-security


【解决方案1】:

最简单的方法是在控制器内部的 updateComment 函数中执行逻辑。因为,你可以很容易地从action参数中获取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;
}

【讨论】:

  • 谢谢,我想我会这样!还有一个问题,如何在我的服务类中获得身份验证..或者可能是方法?
  • 您可以从 SecurityContextHolder.getContext().getAuthentication() 中获取。等等,我将使用您可以使用的完整功能更新答案。 :)
猜你喜欢
  • 1970-01-01
  • 2015-01-29
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 2014-06-02
  • 2013-08-02
  • 1970-01-01
相关资源
最近更新 更多