How to allow a User only access their own data in Spring Boot / Spring Security?

后端 未结 3 520
情歌与酒
情歌与酒 2020-12-05 12:19

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 u

3条回答
  •  甜味超标
    2020-12-05 12:53

    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
            ....
        }
    

    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. Create a bean
        @Component("userSecurity")
        public class UserSecurity {
             public boolean hasUserId(Authentication authentication, Long userId) {
                // do your check(s) here
            }
        }
    
    1. Use your expression
        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)
    

提交回复
热议问题