I am using Jackson to serialize objects to be saved on MongoDB (through Jongo). These objects contain a password hash that I want to store on the database.
I also have a REST API that will return those objects. When the objects are serialized through the REST API they will contain the password hash. Despite the communication being done over HTTPS, this sounds like a security risk to me. How can I prevent the serialization of the password hash through the REST API but not for database persistence? Is there something like conditional serialization of fields?
@JsonView may suit your need.
// View definitions:
class Views {
static class Public { }
static class Internal extends Public { }
}
public class User {
// Name is public
@JsonView(Views.Public.class) String name;
// Hash password only for internal usage
@JsonView(Views.Internal.class) String hashPassword;
}
In your REST API, you could specify:
public class Resource {
@JsonView(Views.Public.class)
@GET
@Produces(MediaType.APPLICATION_JSON )
public List< User > getElements() {
//do something
return someResultList;
}
}
The above api would only include "name" property of User in the response.
Note: If no view annotation, assumed to mean View identified by Object.class: that is, included in all views.
When serializing to DB, you could do this:
objectMapper.viewWriter(Views.Internal.class).writeValue(out, beanInstance);
Which would include all properties of User.
More info here: http://wiki.fasterxml.com/JacksonJsonViews
use this annotation on the password field in the object:
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With