杰克逊·杰森(Jackson Json)序列化:排除与登录用户角色有关的属性 [英] Jackson Json serialization: exclude property respect to the role of the logged user

查看:105
本文介绍了杰克逊·杰森(Jackson Json)序列化:排除与登录用户角色有关的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果登录的用户没有查看特定字段的权限,是否有任何方法可以动态地将Bean属性从序列中排除?

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?

例如,如果一个bean有A,B,C字段,那么在REST响应中,管理员可以看到A,B,C字段,而一个简单的用户只能看到A,B字段.我如何注释字段C的吸气剂?我可以将此类注释与Jersey的SecurityContext集成吗?

For example, if a bean has fields A,B,C may be that, in the REST response, the admin can see fields A,B,C while a simple user can see only fields A,B. How could I annotate the getter of field C? Can I integrate such annotation with the SecurityContext of Jersey?

我正在使用Jersey 2.1和Jackson.

I am using Jersey 2.1 and Jackson.

谢谢

推荐答案

一种可能的方法是使用 JacksonJsonViews ).

One possible approach would be to use @JsonView (see also JacksonJsonViews).

观看次数:

// 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;
}

您需要创建一个 ContextResolver ,如用户指南中 Jackson 部分所述.您可以将 SecurityContext 注入到此ContextResolver,您可以从中找到用户的角色.您的ContextResolver可能看起来像:

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<ObjectMapper> {

    @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;
    }
}

已经针对类似(更用户友好)的用例提交了RFE(请参阅 JERSEY- 2013 ).

这篇关于杰克逊·杰森(Jackson Json)序列化:排除与登录用户角色有关的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆