如何保护SpringBoot/Spring-Data Rest,以便用户只能访问自己的实体

dal*_*lcu 6 spring-mvc spring-security spring-data spring-data-rest

我正在使用Spring-Data/Rest(http://docs.spring.io/spring-data/rest/docs/current/reference/html/)和Spring Boot以及基本的Spring Security.

我有以下实体.

Items
  -->ID

User
 --> ID
 --> List<Items> items
Run Code Online (Sandbox Code Playgroud)

目前有弹簧休息,任何用户都可以看到/ items/1,2,3,4,5

我只想让用户,只看到自己的项目.

这是否可以实现而无需编写自定义控制器?

Ash*_*Rao -1

是的,你可以。

为此,您可以做的是为每个用户分配一个特定的角色。例如,在您的情况下,将拥有项目的用户分配为角色列 ADMIN 和所有其他 ANONYMOUS 或 USER,您选择。之后,使用 spring security 您可以使对于项目 URL 具有 ANONYMOUS 或 USER 角色的用户,请求会失败,并且仅允许具有 ADMIN 角色的用户查看项目。

现在,这可以通过 Spring Security 以多种方式实现:

1.对各个控制器方法使用 @PreAuthorize 标签并测试角色 ADMIN/USER/.. 但是,我猜,您不想大幅修改控制器。

  1. 简短的手动方法,即将身份验证对象创建到上下文持有者中并使用 Spring Boot 安全配置,如下所示:

     @Order(1)
     public class UserFilter extends Filter {
    
     @Autowired
     UserService userService;
     ...
    
     UserObject userObject = userService.getUser(arg..);
     List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
     grantedAuthorityList.add( new SimpleGrantedAuthority((userObject.getRoleName()));//Either ROLE_ADMIN or ROLE_USER
    Authentication authentication = new    PreAuthenticatedAuthenticationToken(userObject.getId(), new Object(), grantedAuthorityList);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(request,response);
    
    ...
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

以及安全配置类:

  @Configuration
  @EnableWebSecurity
  public class SecurityConfigREST extends WebSecurityConfigurerAdapter {


  SecurityConfigREST(){
    super(true);
  }
  @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    PreAuthenticatedAuthenticationProvider pap=new PreAuthenticatedAuthenticationProvider();
    pap.setPreAuthenticatedUserDetailsService(new PreAuthenticatedGrantedAuthoritiesUserDetailsService());
    auth.authenticationProvider(pap);
}
@Override
  protected void configure(HttpSecurity http) throws Exception {
   http
      .authorizeRequests()
      .regexMatchers("^/items.*$").hasAuthority("ROLE_ADMIN") //The role which should have access to /items/1,2.. URL
      .anyRequest().authenticated();
  }
  } 
Run Code Online (Sandbox Code Playgroud)
  1. 在上面的安全配置中使用 UserDetailsS​​ervice 并在预身份验证的身份验证提供程序中加载用户及其角色。请参阅:http://docs.spring.io/autorepo/docs/spring-security/3.2.2.RELEASE/apidocs/org/springframework/security/core/userdetails/UserDetailsS ​​ervice.html

话虽如此,不通过 URL 传递项目 (1,2,3) 数字也是一个很好的设计,因为以后可能会导致潜在的问题,因此使用 GET 并将 JSON 请求正文传递给它,例如:

/items RequestMethod.GET 

{
"itemList" : [1,2,3,4,5]
}

Hope that helps.
Run Code Online (Sandbox Code Playgroud)

  • 是的,应该是“不*不*属于他自己”,但看起来SO在一段时间后不允许编辑评论。是的,角色很好,我确实使用它们。但这与问题中的情况无关。问题是 spring-data-rest 使所有存储库在映射“/{repository}”下可用,从而允许访问所有实体。所以问题是如何只返回属于用户的实体。 (2认同)