且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何允许用户仅在Spring Boot/Spring Security中访问他们自己的数据?

更新时间:2023-11-04 16:36:10

在任何带有@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)