简体   繁体   English

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

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

Let's consider basic authentication flow.让我们考虑基本的身份验证流程。 User A should be able to access entities only with IDs 1 and 2, and user B should be able to access only IDs 3 and 4.用户 A 应该只能访问 ID 为 1 和 2 的实体,用户 B 应该只能访问 ID 为 3 和 4 的实体。

Put it another way, I want user A to be able to access /foos/1 and foos/2 , but get a 401 if trying to call foos/3 .换句话说,我希望用户 A 能够访问/foos/1foos/2 ,但如果尝试调用foos/3则会得到 401。

The way I consider implementing it is getting the current user ID in the endpoint, checking which IDs are mapped to it, and if the requested resource ID is not in that list, throw an unauthorized exception.我考虑实现它的方式是在端点中获取当前用户 ID,检查哪些 ID 映射到它,如果请求的资源 ID 不在该列表中,则抛出未经授权的异常。 Something like this:像这样的东西:

@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 
}

It feels like there should be a more streamlined way to do this.感觉应该有一种更精简的方法来做到这一点。 Is there a better way?有没有更好的办法? How should I protect a user-specific resource from being retrieved by another user?我应该如何保护用户特定的资源不被其他用户检索?

The way you consider to do it is fine...你认为这样做的方式很好......

Another way is to use SpEL directly in the FooRepository ref: jpa.query.spel-expressions另一种方法是直接在 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