Is there any way to dynamically exclude a bean property from being serialized if the logged user has not the permissions to see a specific field?
For example, if a bean
One possible approach would be to use @JsonView (see also JacksonJsonViews).
Views:
// View definitions:
class Views {
static class User { }
static class Admin extends User { }
}
Bean:
public class Bean {
@JsonView(Views.User.class)
private A a;
@JsonView(Views.User.class)
private B b;
@JsonView(Views.Admin.class)
private C c;
}
You would need to create a ContextResolver as described in Jackson section in the user guide. You can inject SecurityContext to this ContextResolver
from which you can find out what role is a user in. Your ContextResolver
may look like:
@Provider
public class MyObjectMapperProvider implements ContextResolver {
@Context
private SecurityContext securityContext;
@Override
public ObjectMapper getContext(Class> type) {
final ObjectMapper objectMapper = new ObjectMapper();
if (securityContext.isUserInRole("admin")) {
objectMapper.getSerializationConfig().setSerializationView(Views.Admin.class);
} else {
objectMapper.getSerializationConfig().setSerializationView(Views.User.class);
}
return objectMapper;
}
}
There is a RFE filed for a similar (more user friendly) use case already (see JERSEY-2013).