同一实体的两个存储库,一个导出,一个未导出 [英] Two repos for the same entity, one exported and one not

查看:17
本文介绍了同一实体的两个存储库,一个导出,一个未导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Sring Data JPA、Spring Data REST 2.4.2、Spring Security 和 Spring Boot 1.3.1.我有一个帐户实体,我想出于管理目的通过 REST 公开:

Using Sring Data JPA, Spring Data REST 2.4.2, Spring Security and Spring Boot 1.3.1. I have an Account entity that I want to expose over REST for admin purposes:

@PreAuthorize("hasRole('ROLE_ADMIN')")  //exclusive admin access
public interface AccountRepository extends JpaRepository<Account, Long> {}

这按预期工作,我可以使用适当的管理员角色访问 REST 界面.

This works as expected and I can access the REST interface with a proper admin role.

我的另一个要求是允许非管理员用户通过 HTTP 进行注册和身份验证.为此,我创建了一个自定义控制器,它通过/register 和/login 资源公开 register() 和 login() 功能.问题在于,当注册/登录内部逻辑与上述 repo 交互时,除了匿名上下文之外,没有可以附加的用户安全上下文.

Another requirement I have is to allow non-admin users to register and authenticate over HTTP. For that I've created a custom Controller that exposes register() and login() functionality over /register and /login resources. The issue is that when the registration/login internal logic interacts with the repo above, there is no user security context that can be attached, apart from an anonymous one.

为了简单起见,我创建了第二个未导出且没有安全要求的存储库:

To keep things simple I have created a second repo that is not exported and has no security requirements:

@RepositoryRestResource(exported = false)
public interface AccountRepositoryInternal extends JpaRepository<Account, Long> {}

然后这个 repo 被注入到所述控制器中.

This repo is then then injected in the said controller.

问题是我看到导出接口的行为不一致.在某些运行时环境中,接口是通过 REST 导出的,而在其他环境中则不是.我可以使用更好的策略吗?

The issue is that I see inconsistent behaviour with the exported interface. In some runtime environments the interface is exported over REST and in others it is not. Is there a better strategy I could use?

推荐答案

您可以在类和方法级别添加 @PreAuthorize,因此如果您只需要某些方法,请确保:>

You can add @PreAuthorize at both class and method level, so if you need only some methods do be secured just:

  1. 只使用一个仓库而不是两个
  2. 扩展 Repository 而不是 JPARepository
  3. PagingAndSortingRepository 复制和粘贴(字面意思,它们只是占位符)您需要的所有方法.

  1. Use only one repo instead of two
  2. Extend Repository instead that JPARepository
  3. Copy and paste (literally, they are just placeholders) all the methods that you need from PagingAndSortingRepository.

根据您的需要将 @PreAuthorize 添加到特定方法,而不是类.

Add @PreAuthorize accordingly to your needs to specific methods, not to the class.

在存储库接口之间复制和粘贴方法是文档建议的(http://docs.spring.io/spring-data/jpa/docs/1.9.2.RELEASE/reference/html/#repositories.definition-tuning) 如果你想有一个细粒度的控制,比如你的情况.

Copying and pasting methods among repositories interfaces is what the docs suggests (http://docs.spring.io/spring-data/jpa/docs/1.9.2.RELEASE/reference/html/#repositories.definition-tuning) if you want to have a fine grained control, such as in you case.

这篇关于同一实体的两个存储库,一个导出,一个未导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆