【发布时间】:2022-01-23 17:20:18
【问题描述】:
我不知道如何用谷歌搜索这个“问题”,所以我创建了这个问题。
我正在构建的应用程序具有以下数据库结构(为示例而简化)。
- Lab1
- Users
- User1
- User2
- Products
- Product1
- Lab2
- Users
- User3
- Products
- Product2
Endpoints:
- ../{labId}/products
- ../products/{id}
- ../{labId}/a
- ../{labId}/b
- ../{labId}/c
- ../{labId}/d
- ../{labId}/...
用户应该只能访问他分配到的实验室的数据。用户 3 应该无法从产品 1 中获取产品数据。
我创建了一个函数来查询数据库以检查用户是否确实与请求的实验室相关联,但我必须在每个端点上调用此函数。这将导致此函数每分钟被调用一千次,因为用户执行的每个查询都将与实验室相关联。这也导致了很多重复的代码。
应用程序目前通过使用带有 JWT 的 spring security 来保护应用程序,并且还具有 RBAC 来拒绝某些用户访问某些资源。
有没有办法使用注释来解决这个问题,我的数据库结构不是最优的还是我的方法正确?
非常感谢!
编辑:端点的示例屏幕截图,productrepository 是一个基本的 JPA 存储库。
我担心 getLabAssociatedWithEntity / userBelongsToLab 方法的重复,想知道这是否是不好的做法。
@GetMapping("/{id}")
fun getProductById(@PathVariable id: Long): ResponseEntity<Product> {
val lab = getLabAssociatedWithProduct(id)
if (userBelongsToLab(SecurityContextHolder.getContext().authentication.name, lab.id)) {
return ResponseEntity.ok().body(productService.getProductById(id))
}
return ResponseEntity(HttpStatus.UNAUTHORIZED)
}
Productservice
fun getProductById(id: Long): Product {
return productRepository.findById(id).orElseThrow { ResourceNotFoundException("Product not found with id: $id") }
}
【问题讨论】:
-
你在使用 Spring Data 吗?如果是这样,您可以将其与 Spring Security 集成,并且在查询中您可以使用当前登录的用户进行过滤。
-
@MarcusHertdaCoregio 我认为他以某种方式错过了关联,让我们看看
-
是的,我正在使用弹簧数据
标签: spring-boot spring-security authorization