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

后端 未结 3 518
情歌与酒
情歌与酒 2020-12-05 12:19

I have some rest api like this:

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

How I must secure them? every u

3条回答
  •  生来不讨喜
    2020-12-05 12:43

    You can also use @PreAuthorize on the service interface. If you have a custom userdetails object then you can do it easily. In one of my projects I did it like this:

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

    BTW this is in a service interface. You have to make sure to add the right annotations to get preauthorize to work.

提交回复
热议问题