如何为单个用户处理多个元素的不同角色?

How to handle different roles for multiple elements for a single user?

首先,我是 spring-boot 和 spring-security 的新手。 我已经阅读了很多文档(尤其是 http://www.spring.io) but I don't find a lot of information. I'm also working with JsonWebTokens, so all my authentication process is based on this. I followed this excellent tutorial to implement JsonWebToken authentication with spring-security : http://blog.jdriven.com/2014/10/stateless-spring-security-part-2-stateless-authentication/

所以这是我的问题: 我正在开发一个错误跟踪应用程序。对于每个项目,多个用户可能具有不同的角色(记者、开发人员、管理员等)。在上述教程中,权限是对整个restfulAPI授予的,用户对整个API只有一个角色。但是,就我而言,我需要首先检查用户是否对好项目有好角色(项目是通过 http 查询参数发送的),我不知道如何处理这个。总而言之,用户可以在一个项目上调用像 /tickets/close/{id} 这样的 URI,但不能在另一个项目上调用。

目前,我的 WebSecurityConfigurerAdapter 重写了 configure() 方法,例如:

http
...
.antMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
.anyRequest().hasAuthority("ROLE_USER").and()
...

但在那种情况下它显然不会处理查询参数。

您所追求的不是 "different roles" 用户,而是授权用户访问一个对象或一组对象。

仔细阅读Domain ACLs,您的用户对不同项目的授权将不同,项目将是问题的父授权对象,问题将从项目继承。

由于您的安全规则需要考虑您的应用程序域,我会在您的控制器中实施安全规则。如果您的控制器检测到用户正在尝试访问被禁止的资源,您将通过 ResponseEntity 响应 503 错误。

我通常做的是从我的控制器中抛出一个自定义异常并定义一个异常处理程序。该异常处理程序将处理 503 响应。这是一个例子:

@ControllerAdvice
public class ExceptionHandlerConfig {
  @ExceptionHandler(ValidationException.class)
  public ResponseEntity<Error> handleInvalidFileFormatException(HttpServletRequest request, RuntimeException ex) {
    Error error = new Error(0, new Date(), request.getRemoteAddr(), request.getRemoteHost(),
    request.getHeader("User-Agent"), ex.getMessage(), ExceptionUtils.getFullStackTrace(ex));

    if (ex instanceof ValidationException) {
        return new ResponseEntity<Error>(error, HttpStatus.BAD_REQUEST);
    }

    LOGGER.error("Error while processing request.", ex);

    return new ResponseEntity<Error>(errorService.save(error), HttpStatus.INTERNAL_SERVER_ERROR);
  }
}

这是一个自定义的 ValidationException 处理程序,它生成 500 HTTP 响应,错误消息包含在 JSON 对象中。您可以使用自定义 SecurityException 为自己重用它,并使用 503 而不是 500 标记 ResponseEntity。

祝你好运。

编辑:ACL 无疑是将您的业务逻辑与安全方面进行适当隔离的最佳选择。但是,如果您不熟悉 Spring 安全高级概念,设置起来可能会很复杂。