如何允许用户仅在 Spring Boot / Spring Security 中访问自己的数据?

How to allow a User only access their own data in Spring Boot / Spring Security?

我有一些休息api像这样:

/users/{user_id}
/users/{user_id}/orders
/users/{user_id}/orders/{order_id}

我必须如何保护它们?每个用户只能看到 her/his 数据,但管理员可以看到所有数据。

我必须在 Spring 中实现的方式和内容 Id == 1 的用户无法看到 Id == 2 的用户的数据,反之亦然,期望角色 admin 的用户可以看到所有?

我是否在会话中的每个方法用户 ID 与传递给 api 的 user_id 参数相等之前检查?有没有更好的方法?

p.s:我通过 spring 安全性使用 JWT。

在任何 @Controller@RestController 注释 bean 中,您可以直接使用 Principal 作为方法参数。

    @RequestMapping("/users/{user_id}")
    public String getUserInfo(@PathVariable("user_id") Long userId, Principal principal){
        // test if userId is current principal or principal is an ADMIN
        ....
    }

如果您不想在 Controller 中进行安全检查,您可以使用 Spring EL 表达式。 您可能已经使用了一些内置表达式,例如 hasRole([role]).

并且您可以编写自己的表达式。

  1. 创建 bean
    @Component("userSecurity")
    public class UserSecurity {
         public boolean hasUserId(Authentication authentication, Long userId) {
            // do your check(s) here
        }
    }
  1. 使用你的表达方式
    http
     .authorizeRequests()
     .antMatchers("/user/{userId}/**")
          .access("@userSecurity.hasUserId(authentication,#userId)")
        ...

好消息是您还可以组合以下表达式:

    hasRole('admin') or @userSecurity.hasUserId(authentication,#userId)

您也可以在服务接口上使用@PreAuthorize。如果您有一个自定义的 userdetails 对象,那么您可以轻松地做到这一点。 在我的一个项目中,我是这样做的:

@PreAuthorize(value = "hasAuthority('ADMIN')"
        + "or authentication.principal.equals(#post.member) ")
void deletePost(Post post);

顺便说一句,这是在服务界面中。您必须确保添加正确的注释才能获得预授权。

您应该首先选择您的安全策略, What you need names "Row Filtering", Authorization Concepts of 3A( Authentication, Authorization,Audit ) 概念之一。

如果您想实施全面的解决方案,请查看:

https://docs.spring.io/spring-security/site/docs/3.0.x/reference/domain-acls.html

Spring ACL 完全涵盖了 "Row Filtering"、"White-Black List"、"Role Base Authorization"、"ACL Inheritance"、"Role Voter"、....

否则,您应该保存每个要保护的业务案例的所有者,并在您的服务层中过滤它们。

我们可以创建一个像 @IsUser 这样的注解,并将其与控制器方法一起使用。

示例:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize(value = "hasRole('ROLE_USER')" + "and authentication.principal.equals(#userId) ")
public @interface IsUser { }