【问题标题】:How to allow some User only access his own data in endpoint in Spring Boot / Spring Security with pagination?如何通过分页允许某些用户仅在 Spring Boot / Spring Security 的端点中访问他自己的数据?
【发布时间】:2022-07-05 21:09:50
【问题描述】:

我有一个关于在我的应用程序中将产品列表限制为特定用户的问题。我有一个 API:“/api/v1/{userId}/products”,我想在我已经在 AdminRestController 中使用过的 UserRestController 中使用分页:

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

我已经阅读了一些主题并找到了一些使用“@PreAuthorize("#userId == authentication.principal.id")”的解决方案。现在,我想在 UserRestController 的端点中实现分页,它应该只返回与特定用户相关的产品列表(而不是所有产品的列表)。我尝试使用以下内容:

@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));
}

但是我遇到了访问问题,你能帮我弄清楚吗?

提前致谢!

【问题讨论】:

    标签: java spring spring-boot spring-security pagination


    【解决方案1】:

    它已经在Spring-SecutirySpring-Data 中实现。

    在配置中,您需要添加一个@Bean 以将您的principal 提供到查询中:

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

    之后你就可以写这样的东西了:

    @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);
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 2019-01-13
      • 1970-01-01
      • 2016-09-14
      • 2015-05-25
      • 2019-07-21
      • 1970-01-01
      • 2017-04-17
      • 2012-05-31
      • 2018-04-03
      相关资源
      最近更新 更多