Jackson Json serialization: exclude property respect to the role of the logged user

前端 未结 2 461
清歌不尽
清歌不尽 2021-01-28 01:41

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

2条回答
  •  执笔经年
    2021-01-28 02:27

    If you use the same JAX-RS resources for requests with different user roles, you should consider the following solution:

    @Provider
    public class SecuritySerializerFilter extends JacksonJaxbJsonProvider {
        @Context
        SecurityContext securityContext;
    
        @Override
        public void writeTo(Object value, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    
            ObjectMapper current = locateMapper(type, mediaType);
            setMapper(current.setSerializationConfig(
                current.getSerializationConfig().withView(
                    securityContext.isUserInRole("admin") ? Views.Admin.class : Views.User.class
                )
            ));
    
            super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
        }
    }
    

提交回复
热议问题