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 user must see only her/his data, But admin can see all of them.
How & What I must implement in Spring Security that User by Id == 1 can't see data of user by Id == 2 and vice versa, expect users by role admin that can see all?
Do I check before every method User Id in session is equail with user_id param passed to api? is there a better way?
p.s: I use JWT by spring security.
You should first choose your security strategy, What you need names "Row Filtering", one of Authorization Concepts of 3A( Authentication, Authorization,Audit ) Concepts.
If you want to implement comprehensive solution, take a look at :
Spring ACL completely covers concepts like "Row Filtering", "White-Black List", "Role Base Authorization", "ACL Inheritance", "Role Voter", ....
Otherwise you should save the owner per business case you want to be secured and filter them in your Service Layer.
In any
@Controller
,@RestController
annotated bean you can usePrincipal
directly as a method argument.If you don't want the security checks in your
Controller
s you could use Spring EL expressions. You probably already use some build-in expressions likehasRole([role])
.And you can write your own expressions.
bean
The nice thing is that you can also combine expressions like:
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:
BTW this is in a service interface. You have to make sure to add the right annotations to get preauthorize to work.