data.adoc 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. [[data]]
  2. = Spring Data Integration
  3. Spring Security provides Spring Data integration that allows referring to the current user within your queries.
  4. 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.
  5. [[data-configuration]]
  6. == Spring Data & Spring Security Configuration
  7. To use this support, add `org.springframework.security:spring-security-data` dependency and provide a bean of type `SecurityEvaluationContextExtension`:
  8. ====
  9. .Java
  10. [source,java,role="primary"]
  11. ----
  12. @Bean
  13. public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
  14. return new SecurityEvaluationContextExtension();
  15. }
  16. ----
  17. .Kotlin
  18. [source,kotlin,role="secondary"]
  19. ----
  20. @Bean
  21. fun securityEvaluationContextExtension(): SecurityEvaluationContextExtension {
  22. return SecurityEvaluationContextExtension()
  23. }
  24. ----
  25. ====
  26. In XML Configuration, this would look like:
  27. ====
  28. [source,xml]
  29. ----
  30. <bean class="org.springframework.security.data.repository.query.SecurityEvaluationContextExtension"/>
  31. ----
  32. ====
  33. [[data-query]]
  34. == Security Expressions within @Query
  35. Now you can use Spring Security within your queries:
  36. ====
  37. .Java
  38. [source,java,role="primary"]
  39. ----
  40. @Repository
  41. public interface MessageRepository extends PagingAndSortingRepository<Message,Long> {
  42. @Query("select m from Message m where m.to.id = ?#{ principal?.id }")
  43. Page<Message> findInbox(Pageable pageable);
  44. }
  45. ----
  46. .Kotlin
  47. [source,kotlin,role="secondary"]
  48. ----
  49. @Repository
  50. interface MessageRepository : PagingAndSortingRepository<Message,Long> {
  51. @Query("select m from Message m where m.to.id = ?#{ principal?.id }")
  52. fun findInbox(pageable: Pageable): Page<Message>
  53. }
  54. ----
  55. ====
  56. This checks to see if the `Authentication.getPrincipal().getId()` is equal to the recipient of the `Message`.
  57. Note that this example assumes you have customized the principal to be an Object that has an id property.
  58. By exposing the `SecurityEvaluationContextExtension` bean, all of the xref:servlet/authorization/expression-based.adoc#common-expressions[Common Security Expressions] are available within the Query.