GLi*_*Boy 4 rest spring spring-security spring-boot spring-security-oauth2
我有一些这样的休息API:
/users/{user_id}
/users/{user_id}/orders
/users/{user_id}/orders/{order_id}
Run Code Online (Sandbox Code Playgroud)
我该如何保护它们?每个用户只能看到她/他的数据,但是管理员可以看到所有这些数据。
我必须如何在Spring Security中实现Id == 1的用户看不到Id == 2的用户数据,反之亦然,希望角色admin的用户可以看到全部?
我是否在将会话中的每个方法用户ID与传递给api的user_id参数等同之前进行检查?有没有更好的办法?
ps:我在Spring Security上使用JWT。
在@Controller,@RestController注释豆你可以使用Principal直接作为方法的参数。
@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
....
}
Run Code Online (Sandbox Code Playgroud)
如果您不想在中进行安全检查,则Controller可以使用Spring EL表达式。您可能已经使用了一些内置表达式,例如hasRole([role])。但您可以编写自己的表达式。
创建一个 bean
public class UserSecurity {
public boolean hasUserId(Authentication authentication, Long userId) {
// do your check(s) here
}
}
Run Code Online (Sandbox Code Playgroud)
用你的表情
http
.authorizeRequests()
.antMatchers("/user/{userId}/**")
.access("@userSecurity.hasUserId(authentication,#userId)")
...
Run Code Online (Sandbox Code Playgroud)
你可以结合像
hasRole('admin') or @userSecurity.hasUserId(authentication,#userId)
小智 6
您还可以在服务接口上使用@PreAuthorize。如果您有自定义 userdetails 对象,那么您可以轻松完成。在我的一个项目中,我是这样做的:
@PreAuthorize(value = "hasAuthority('ADMIN')"
+ "or authentication.principal.equals(#post.member) ")
void deletePost(Post post);
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这是在服务接口中。您必须确保添加正确的注释才能使预授权发挥作用。
| 归档时间: |
|
| 查看次数: |
2168 次 |
| 最近记录: |