Spring Data Integration

Spring Security 提供 Spring Data 集成,它允许在你查询中引用当前用户。在查询中包含用户不仅有用,而且对于支持分页结果也是必需的,因为之后筛选结果无法扩展。

Spring Security provides Spring Data integration that allows referring to the current user within your queries. It is not only useful but necessary to include the user in the queries to support paged results since filtering the results afterwards would not scale.

Spring Data & Spring Security Configuration

要使用此支持,请添加 org.springframework.security:spring-security-data 依赖项并提供 SecurityEvaluationContextExtension 类型 Bean:

To use this support, add org.springframework.security:spring-security-data dependency and provide a bean of type SecurityEvaluationContextExtension:

  • Java

  • Kotlin

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
	return new SecurityEvaluationContextExtension();
}
@Bean
fun securityEvaluationContextExtension(): SecurityEvaluationContextExtension {
	return SecurityEvaluationContextExtension()
}

在 XML 配置中,这看起来像:

In XML Configuration, this would look like:

<bean class="org.springframework.security.data.repository.query.SecurityEvaluationContextExtension"/>

Security Expressions within @Query

现在可以在查询中使用 Spring Security:

Now you can use Spring Security within your queries:

  • Java

  • Kotlin

@Repository
public interface MessageRepository extends PagingAndSortingRepository<Message,Long> {
	@Query("select m from Message m where m.to.id = ?#{ principal?.id }")
	Page<Message> findInbox(Pageable pageable);
}
@Repository
interface MessageRepository : PagingAndSortingRepository<Message,Long> {
	@Query("select m from Message m where m.to.id = ?#{ principal?.id }")
	fun findInbox(pageable: Pageable): Page<Message>
}

这会检查 “@7” 是否等于 “@8” 的接收方。请注意,本示例假定您已将主体自定义为具有 ID 属性的对象。通过公开 “@9” bean,所有 “@10” 都可以在查询中使用。

This checks to see if the Authentication.getPrincipal().getId() is equal to the recipient of the Message. Note that this example assumes you have customized the principal to be an Object that has an id property. By exposing the SecurityEvaluationContextExtension bean, all of the Common Security Expressions are available within the Query.