Data Hiding using JsonIgnore and Spring Data JPA is achieved using two approaches –
This post considers @JsonIgnore and @JsonIgnoreProperties
The code is available at –
I’ve added an extra table to for this example –
@Entity public class Secrets { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; private String mySecrets; public String getMySecrets() { return mySecrets; } public void setMySecrets(String mySecrets) { this.mySecrets = mySecrets; } }
With its associated repository –
@PreAuthorize("hasRole('ROLE_USER')") public interface SecretsRepository extends CrudRepository<Secrets, Long> { }
I have left the security from the last tutorial, Securing Spring Data REST with PreAuthorize, in place – but we can run this code using –
mvnw spring-boot:run
We can then call rest/profile to see the two exposed repositories –
curl -u user:user -X GET http://localhost:8080/rest/profile { "_links" : { "self" : { "href" : "http://localhost:8080/rest/profile" }, "secrets" : { "href" : "http://localhost:8080/rest/profile/secrets" }, "parkrunCourses" : { "href" : "http://localhost:8080/rest/profile/parkrunCourses" } } }
And calling the secrets REST end point-
curl -u user:user -X GET http://localhost:8080/rest/secrets/1 { "mySecret" : "I want to hide this", "_links" : { "self" : { "href" : "http://localhost:8080/rest/secrets/1" }, "secret" : { "href" : "http://localhost:8080/rest/secrets/1" } } }
This posts looks at techniques I can use to not expose the SecretRepository
The purpose of @JsonIgnore, and @JsonIgnoreProperties is to hide attributes from the Jackson parser by instructing it to Ignore these fields
Usage is simply a matter of tagging the attribute with the @JsonIgnore
@Entity public class Secret { // @JsonIgnore private String mySecret; // }
Or we can achieve the same using @JsonIgnoreProperties annotation –
@JsonIgnoreProperties({"mySecret"}) @Entity public class Secret { // private String mySecret; // }
With either of these changes we can then call our secrets REST end point, and the mySecret field is no longer exposed –
curl -u user:user -X GET http://localhost:8080/rest/secrets/1 { "_links" : { "self" : { "href" : "http://localhost:8080/rest/secrets/1" }, "secret" : { "href" : "http://localhost:8080/rest/secrets/1" } } }
@JsonIgnore or @JsonIgnoreProperties simply hides the field from the Jackson parser. This is good for hiding small pieces of information. The downside is we still have an exposed end point due to the default Repository Detection Strategies.