简体   繁体   中英

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.

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 .

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. 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

@Query("select foo from Foo foo where foo.id = ?1 and foo.user.id=?#{principal.id}")
Foo findFooById(String fooId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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