简体   繁体   English

如何通过分页允许某些用户仅在 Spring Boot / Spring Security 的端点中访问他自己的数据?

[英]How to allow some User only access his own data in endpoint in Spring Boot / Spring Security with pagination?

I have a question related to the limiting of the products list to specific User in my application.我有一个关于在我的应用程序中将产品列表限制为特定用户的问题。 Ive got an API: "/api/v1/{userId}/products" and I want to use pagination in my UserRestController which I have already used in AdminRestController:我有一个 API:“/api/v1/{userId}/products”,我想在我已经在 AdminRestController 中使用过的 UserRestController 中使用分页:

@GetMapping
    public Response<Page<Product>> getProductPage(@PageableDefault(sort = "id") Pageable pageable) {
        return Response.ok(productService.findAll(pageable));
    }

I have read some threads and find some solutions with "@PreAuthorize("#userId == authentication.principal.id")".我已经阅读了一些主题并找到了一些使用“@PreAuthorize("#userId == authentication.principal.id")”的解决方案。 Now, I want to implement pagination in my endpoint in UserRestController which should return only the products list related to the specific User (not the list of all products).现在,我想在 UserRestController 的端点中实现分页,它应该只返回与特定用户相关的产品列表(而不是所有产品的列表)。 I have tried to use the following:我尝试使用以下内容:

@GetMapping("/api/v1/{userId}/products")
@PreAuthorize("#userId == authentication.principal.id")
public Response<Page<Product>> getProductPage(@PageableDefault(sort = "id") Pageable pageable) {
    SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return Response.ok(productService.findAll(pageable));
}

But I have got the access problem, could you help me to figure out?但是我遇到了访问问题,你能帮我弄清楚吗?

Thanks in advance!提前致谢!

It is already implemented into Spring-Secutiry and Spring-Data .它已经在Spring-SecutirySpring-Data中实现。

In config, you need to add a @Bean to provide your principal into the queriing :在配置中,您需要添加一个 @Bean 以将您的principal提供到查询中:

@Configuration
public class Conf{
    // `principal` provider for the Spring-Data JPQL requests
    @Bean
    public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
      return new SecurityEvaluationContextExtension();
    }
}

After that you'll be abble to write things like that :之后你就可以写这样的东西了:

@RepositoryRestResource(path = "datas", exported = true)
public interface DataRepository extends PagingAndSortingRepository<Data, Long> {

  @Override
  @Query(value = "Select d From Data d Where d.ownerId = ?#{principal?.username}")
  Page<Data> findAll(Pageable pageable);

}

Also, read the official doc : https://docs.spring.io/spring-security/reference/features/integrations/data.html另外,请阅读官方文档: https ://docs.spring.io/spring-security/reference/features/integrations/data.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM