1

让我们考虑基本的身份验证流程。用户 A 应该只能访问 ID 为 1 和 2 的实体,用户 B 应该只能访问 ID 为 3 和 4 的实体。

换句话说,我希望用户 A 能够访问/foos/1and foos/2,但如果尝试调用 ,则会得到 401 foos/3

我考虑实现它的方式是在端点中获取当前用户 ID,检查哪些 ID 映射到它,如果请求的资源 ID 不在该列表中,则抛出未经授权的异常。像这样的东西:

@GetMapping("/foo/{fooId}")
public Foo home(@AuthenticationPrincipal User user, @PathVariable String fooId) {
   // Get Foo IDs mapped to User
   // If fooId is not in the result, throw an unauthorized exception 
}

感觉应该有一种更精简的方法来做到这一点。有没有更好的办法?我应该如何保护用户特定的资源不被其他用户检索?

4

1 回答 1

1

你认为这样做的方式很好......

另一种方法是直接在 FooRepository ref 中使用 SpEL:jpa.query.spel-expressions

@Query("select foo from Foo foo where foo.id = ?1 and foo.user.id=?#{principal.id}")
Foo findFooById(String fooId);
于 2020-06-05T13:58:01.370 回答