Spring security SpringDataREST:基于安全性的投影
我正在使用和的当前版本,并拥有以下实体:Spring security SpringDataREST:基于安全性的投影,spring-security,jackson,spring-data-jpa,spring-data-rest,Spring Security,Jackson,Spring Data Jpa,Spring Data Rest,我正在使用和的当前版本,并拥有以下实体: public class User { @Id @GeneratedValue private Long id; private String name; private String password; private String email; ...getter/setter methods... } 我还使用了Spring-Security 我的用户存储库: @RepositoryRe
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String password;
private String email;
...getter/setter methods...
}
我还使用了Spring-Security
我的用户存储库:
@RepositoryRestResource(
collectionResourceRel = "user",
path = "user",
excerptProjection = UserSimpleProjection.class)
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
还有一个细节:
@Projection(name = "detailed", types = User.class)
public interface UserDetailProjection extends UserSimpleProjection{
public String getEmail();
}
到目前为止还不错,根据我的要求,我得到了不同的结果
是否有办法根据Spring安全性自动切换投影和/或限制不同角色的不同投影?否,Spring Data REST投影不支持此功能。您可以在投影中添加一个“虚拟”值属性,通过安全检查调用服务方法:
@Projection(name = "detailed", types = User.class)
public interface UserDetailProjection extends UserSimpleProjection{
@Value("#{@userService.checkAccess(target)? target.email : null}")
public String getEmail();
}
如果您的自定义UserService
组件在checkAccess(…)
上有@PreAuthorize
以抛出AccessDeniedException
任何对您更有利的选项,则该组件将返回true
注意,SpEL中的
target
属性保存原始对象-由Spring数据提供。您也可以使用Spring安全配置中的
.regexMatchers(HttpMethod.GET,"/user/.*projection=simple.*").hasRole("ROLE_ADMIN")
你有没有根据角色进行预测?没有,对不起。我当时放弃了,做了自定义控制器。为什么这个@Value(#{principal.username.equalsIgnoreCase('admin')?target.password:null})不起作用,因为
principal
不是这个上下文中使用的SpEL根对象的属性。要访问bean,可以使用@
前缀。请阅读有关SpEL的更多信息:注意,在SpEL中,您可以使用变量(#myvar
)、bean(@mybean
)、“根对象”属性和方法等。还请注意,表达式在不同的上下文中具有不同的“根对象”,这些上下文由某些处理程序设置。例如,@PreAuthorize
由MethodSecurityExpressionHandler
处理,投影@Value
-由SpelAwareProxyProjectionFactory
处理。您可以查看源代码以供参考。
.regexMatchers(HttpMethod.GET,"/user/.*projection=simple.*").hasRole("ROLE_ADMIN")