Home > Mobile >  Dividing access rights between each user in Spring Security
Dividing access rights between each user in Spring Security

Time:04-19

I have a problem trying to understand spring security.

I've found a lot of tutorials that tell how to give different roles to different users and then use antMatchers() to give differen access rights.

But I wonder what to do if I want to give different access rights to each user.

E.g. /api/user/{user_id} and I do not want to let access for that endpoint to anyone except user with corresponding id.

CodePudding user response:

You can use @PreAuthorize to restrict access to certain methods, but for further information, consult the documentation.

https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html

CodePudding user response:

You can retrieve the currently logged-in user user_id using Principal class and you can check.
you can refer to the sample code.

 @RequestMapping("/api/users/{user_id}")
    public String method1(@PathVariable("user_id") Long userId, Principal principal){
        // you can test the currently logged in user using Principal and user_id
        ....
    }
  • Related