如何允许用户仅在Spring Boot/Spring Security中访问他们自己的数据? [英] How to allow a User only access their own data in Spring Boot / Spring Security?

查看:359
本文介绍了如何允许用户仅在Spring Boot/Spring Security中访问他们自己的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的rest 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?

p.s:我在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 Controllers you could use Spring EL expressions. You probably already use some build-in expressions like hasRole([role]).

您可以编写自己的表达式.

And you can write your own expressions.

  1. 创建一个bean

    @Component("userSecurity")
    public class UserSecurity {
         public boolean hasUserId(Authentication authentication, Long userId) {
            // do your check(s) here
        }
    }

  1. 使用您的表情

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆