簡體   English   中英

如何通過分頁允許某些用戶僅在 Spring Boot / Spring Security 的端點中訪問他自己的數據?

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

我有一個關於在我的應用程序中將產品列表限制為特定用戶的問題。 我有一個 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));
}

但是我遇到了訪問問題,你能幫我弄清楚嗎?

提前致謝!

它已經在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM