![](/img/trans.png)
[英]How to allow anonymous user access from localhost only in 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-Secutiry
和Spring-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.