2021-11-10 15:38:29 -07:00
[[data]]
= Spring Data Integration
Spring Security provides Spring Data integration that allows referring to the current user within your queries.
2021-04-21 16:01:26 -05:00
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.
2021-11-10 15:38:29 -07:00
[[data-configuration]]
== Spring Data & Spring Security Configuration
2021-04-21 16:01:26 -05:00
To use this support, add the `org.springframework.security:spring-security-data` dependency and provide a bean of type `SecurityEvaluationContextExtension`.
In Java configuration, this would look like:
2021-11-10 15:38:29 -07:00
2021-04-21 16:01:26 -05:00
====
2021-11-10 15:38:29 -07:00
[source,java]
----
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
----
2021-04-21 16:01:26 -05:00
====
2021-11-10 15:38:29 -07:00
In XML Configuration, this would look like:
2021-04-21 16:01:26 -05:00
====
2021-11-10 15:38:29 -07:00
[source,xml]
----
<bean class="org.springframework.security.data.repository.query.SecurityEvaluationContextExtension"/>
----
2021-04-21 16:01:26 -05:00
====
2021-11-10 15:38:29 -07:00
[[data-query]]
== Security Expressions within @Query
2021-04-21 16:01:26 -05:00
Now you can use Spring Security within your queries:
2021-11-10 15:38:29 -07:00
2021-04-21 16:01:26 -05:00
====
2021-11-10 15:38:29 -07:00
[source,java]
----
@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);
}
----
2021-04-21 16:01:26 -05:00
====
2021-11-10 15:38:29 -07:00
This checks to see if the `Authentication.getPrincipal().getId()` is equal to the recipient of the `Message`.
2021-04-21 16:01:26 -05:00
Note that this example assumes you have customized the principal to be an `Object` that has an `id` property.
2021-12-13 16:57:36 -06:00
By exposing the `SecurityEvaluationContextExtension` bean, all of the xref:servlet/authorization/expression-based.adoc#common-expressions[Common Security Expressions] are available within the query.