如何在 Spring Boot/Spring Security 中允许用户只访问他们自己的数据? [英] How to allow a User only access their own data in Spring Boot / Spring Security?
问题描述
我有一些像这样的休息 api:
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.
如何&我必须在 Spring Security 中实现的是,Id == 1 的用户无法看到 Id == 2 的用户数据,反之亦然,期望角色 admin 的用户可以看到所有内容?
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?
我是否在会话中的每个方法用户 ID 与传递给 api 的 user_id 参数相等之前检查?有没有更好的办法?
Do I check before every method User Id in session is equail with user_id param passed to api? is there a better way?
ps:我通过 spring security 使用 JWT.
p.s: I use JWT by spring security.
推荐答案
在任何 @Controller
, @RestController
注释的 bean 中你都可以使用 Principal
直接作为方法参数.
In any @Controller
, @RestController
annotated bean you can use Principal
directly as a method argument.
@RequestMapping("/users/{user_id}")
public String getUserInfo(@PathVariable("user_id") Long userId, Principal principal){
// test if userId is current principal or principal is an ADMIN
....
}
如果您不想在 Controller
中进行安全检查,您可以使用 Spring EL 表达式.您可能已经使用了一些内置表达式,例如 hasRole([role])
.
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 like hasRole([role])
.
并且您可以编写自己的表达式.
And you can write your own expressions.
- 创建一个
bean
@Component("userSecurity")
public class UserSecurity {
public boolean hasUserId(Authentication authentication, Long userId) {
// do your check(s) here
}
}
- 用你的表情
http
.authorizeRequests()
.antMatchers("/user/{userId}/**")
.access("@userSecurity.hasUserId(authentication,#userId)")
...
好处是您还可以组合以下表达式:
The nice thing is that you can also combine expressions like:
hasRole('admin') or @userSecurity.hasUserId(authentication,#userId)
这篇关于如何在 Spring Boot/Spring Security 中允许用户只访问他们自己的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!