What are the architectural and security trade-offs of auto-exposing repositories with Spring Data REST, and when would you choose it over hand-written controllers?
answer
- API contract = your entity model (coupling)
- exposed-by-default -> security is opt-in
- harden: ANNOTATED + exported=false + @PreAuthorize + @Projection
- great for admin/internal CRUD, bad for public versioned API
- blend: SDR for CRUD, controllers for behavior
basics
~20 sAuto-exposure is fast but tightly couples your HTTP API to your persistence model and exposes everything by default, which is a security and contract risk. Use it for internal/admin CRUD; prefer DTO-based controllers when you need a stable public contract, custom validation, or business logic.
solid answer
~40 sSpring Data REST's strength — publishing repositories with zero controller code — is also its liability. The API contract becomes your entity model, so schema changes leak into clients and you can accidentally expose fields, associations, and finders. By default every public repository is exposed, so security must be added deliberately: lock down with `RepositoryDetectionStrategies.ANNOTATED` (opt-in whitelist), `exported=false`, method security (`@PreAuthorize` on repository methods, enabled via config), URL rules, and `@Projection`/excerpts to shape output. It shines for admin panels, internal tools, prototypes, and CRUD microservices where mirroring the model is acceptable and hypermedia navigation is valued. Prefer explicit `@RestController` + DTOs when you need a versioned, decoupled public contract, rich validation, non-trivial write logic, or fine control over payload shape. Many teams blend both: SDR for bulk CRUD, custom controllers for behavior.
go deeper
Understand SDR is convenient but exposes a lot automatically, so it isn't automatically safe.
List the main hardening levers (detection strategy, exported=false, projections, security).
Articulate the model-as-contract coupling and choose SDR vs controllers per use case with concrete criteria.
Make an explicit architectural call: bound SDR to internal/controlled CRUD, mandate hardening, and reserve DTO controllers for versioned public contracts; know how to blend both.
**The core tension.** Spring Data REST trades *development speed* for *coupling and control*. Because it derives the HTTP API directly from repositories and entities, the persistence model *is* the API contract. That is wonderful for getting a working, hypermedia-rich CRUD surface in minutes and terrible for long-lived public APIs that must evolve independently of the schema. **Security considerations (the big one).** - **Exposed-by-default:** with the DEFAULT strategy every public repository is published — including ones you forgot about (join tables, audit logs). Mitigate with `RepositoryDetectionStrategies.ANNOTATED` for an explicit whitelist, `@RepositoryRestResource(exported=false)` / `@RestResource(exported=false)`, or package-private repositories. - **Authorization:** SDR endpoints are ordinary Spring MVC handlers, so Spring Security URL rules apply, but for fine-grained control you enable method security and annotate repository methods with `@PreAuthorize`/`@PostAuthorize` (e.g. `@PreAuthorize("hasRole('ADMIN')")` on `save`/`delete`). Without this, exposed writes are open. - **Over-exposure of data:** entities may carry sensitive fields; use `@Projection` interfaces (and excerpt projections) plus Jackson annotations (`@JsonIgnore`) to shape responses, and validate/limit writable fields. - **Enumeration & mass finders:** exported derived finders can leak query capability; hide sensitive ones with `exported=false`. **Contract & evolution.** Renaming an entity field renames a JSON property; renaming a repository path or a `rel` breaks clients. There's no built-in versioning story, so decoupling for backward compatibility is manual. DTO controllers give you an explicit, versionable boundary. **Where SDR fits well.** - Internal admin consoles and back-office CRUD. - Rapid prototypes and spikes. - Microservices whose HTTP surface is genuinely a thin CRUD veneer over the model, where HAL navigation is a plus and clients are internal/controlled. **Where hand-written controllers win.** - Public/partner APIs needing a stable, versioned contract independent of the schema. - Rich input validation, complex authorization, transactional business logic on writes. - Bespoke payload shapes, aggregation across aggregates, non-CRUD operations. **Blended approach (common in practice).** Expose safe read/CRUD repositories via SDR, harden them (ANNOTATED + method security + projections), and add `@RepositoryRestController`/`@BasePathAwareController` or plain `@RestController`s for custom operations that live alongside SDR endpoints under the same base path. A hand-written controller mapped to an SDR path takes precedence, letting you override specific operations selectively. **Operational notes.** SDR integrates with the ALPS/`profile` metadata, supports CORS via `RepositoryRestConfigurer`, and honors HAL; but observability, custom error contracts, and payload validation often require extra work compared to controllers you fully own. The principal-level judgment is: adopt SDR where the model-as-API coupling is acceptable and the surface is internal or controlled; avoid it as the foundation of a long-lived public contract.
- How do you enforce that only admins can DELETE via a Spring Data REST endpoint?Enable method security and put @PreAuthorize("hasRole('ADMIN')") on the repository's delete method (or use Spring Security URL rules on the DELETE path). SDR endpoints are standard secured MVC handlers.
- How do you shape or restrict the fields returned without abandoning SDR?Define @Projection interfaces (and an excerpt projection for collections), request them via ?projection=, and use @JsonIgnore on sensitive fields, so responses don't mirror the full entity.
- You need one custom non-CRUD operation but like SDR for the rest. What do you do?Add a @RepositoryRestController (or @BasePathAwareController) with a handler under the same base path; a hand-written mapping overrides the corresponding SDR endpoint while the rest stay auto-generated.
saying these in an interview costs you the question
- Claiming Spring Data REST is secure by default
- Using it as the basis of a versioned public API without a decoupling layer
- Assuming you can't add custom controllers alongside SDR endpoints