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

独自空忆成欢 提交于 2019-12-05 19:05:34

In a @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 built-in expressions like hasRole([role]). but you could write your own expressions.

Create a bean

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

Use your expression

http
 .authorizeRequests()
 .antMatchers("/user/{userId}/**")
      .access("@userSecurity.hasUserId(authentication,#userId)")
    ...

and you can combine expressions like

hasRole('admin') or @userSecurity.hasUserId(authentication,#userId)

You can also use @PreAuthorize on the service interface. If you have a custom userdetails object then you can do it easily. In one of my projects I did it like this:

@PreAuthorize(value = "hasAuthority('ADMIN')"
        + "or authentication.principal.equals(#post.member) ")
void deletePost(Post post);

BTW this is in a service interface. You have to make sure to add the right annotations to get preauthorize to work.

You should first choose your security strategy, What you need names "Row Filtering", one of Authorization Concepts of 3A( Authentication, Authorization,Audit ) Concepts.

If you want to implement comprehensive solution, take a look at :

https://docs.spring.io/spring-security/site/docs/3.0.x/reference/domain-acls.html

Spring ACL completely covers concepts like "Row Filtering", "White-Black List", "Role Base Authorization", "ACL Inheritance", "Role Voter", ....

Otherwise you should save the owner per business case you want to be secured and filter them in your Service Layer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!