繁体   English   中英

应如何使用 spring 引导安全保护用户特定资源?

[英]How should a user-specific resource be protected using spring boot security?

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

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

我考虑实现它的方式是在端点中获取当前用户 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 
}

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

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

另一种方法是直接在 FooRepository 参考中使用 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM