Spring 3.2:根据Spring Security角色过滤Jackson JSON输出

时间:2013-06-24 12:57:32

标签: spring spring-security jackson

有没有什么好的方法可以根据Spring Security角色过滤JSON输出?我正在寻找像@JsonIgnore这样的东西,但是对于角色,比如@HasRole(“ROLE_ADMIN”)。我该如何实现呢?

3 个答案:

答案 0 :(得分:12)

对于那些从Google登陆的人来说,这是一个与Spring Boot 1.4类似的解决方案。

为每个角色定义界面,例如

public class View {
    public interface Anonymous {}

    public interface Guest extends Anonymous {}

    public interface Organizer extends Guest {}

    public interface BusinessAdmin extends Organizer {}

    public interface TechnicalAdmin extends BusinessAdmin {}
}

在您的实体中声明@JsonView,例如

@Entity
public class SomeEntity {
    @JsonView(View.Anonymous.class)
    String anonymousField;

    @JsonView(View.BusinessAdmin.class)
    String adminField;
}

根据角色定义@ControllerAdvice以选择正确的JsonView

@ControllerAdvice
public class JsonViewConfiguration extends AbstractMappingJacksonResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return super.supports(returnType, converterType);
    }

    @Override
    protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
                                           MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

        Class<?> viewClass = View.Anonymous.class;

        if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) {
            Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();

            if (authorities.stream().anyMatch(o -> o.getAuthority().equals(Role.GUEST.getValue()))) {
                viewClass = View.Guest.class;
            }
            if (authorities.stream().anyMatch(o -> o.getAuthority().equals(Role.ORGANIZER.getValue()))) {
                viewClass = View.Organizer.class;
            }
            if (authorities.stream().anyMatch(o -> o.getAuthority().equals(Role.BUSINESS_ADMIN.getValue()))) {
                viewClass = View.BusinessAdmin.class;
            }
            if (authorities.stream().anyMatch(o -> o.getAuthority().equals(Role.TECHNICAL_ADMIN.getValue()))) {
                viewClass = View.TechnicalAdmin.class;
            }
        }
        bodyContainer.setSerializationView(viewClass);
    }
}

答案 1 :(得分:9)

更新:新答案

您应该考虑使用rkonovalov/jfilter。特别@DynamicFilterComponent帮了很多忙。 你可以在这篇DZone文章中看到一个很好的指南。

@DynamicFilterComponent解释为here

旧答案

我刚刚实施了您上面提到的要求。我的系统使用Restful Jersey 1.17Spring Security 3.0.7Jackson 1.9.2。但该解决方案与Jersey Restful API无关,您可以在任何其他类型的Servlet实现中使用它。

这是我的解决方案的全部5个步骤:

  1. 首先,您应该为您的目的创建一个Annotation类,如下所示:

    JsonSpringView.java

    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    public @interface JsonSpringView {
        String springRoles();
    }
    
  2. 然后是Annotation Introspector,其大部分方法都应该返回null,根据您的需要填写方法,以满足我刚刚使用isIgnorableField的要求。 Feature是我对GrantedAuthority接口的实现。像这样:

    JsonSpringViewAnnotationIntrospector.java

    @Component
    public class JsonSpringViewAnnotationIntrospector extends AnnotationIntrospector implements Versioned 
    {
        // SOME METHODS HERE
        @Override
        public boolean isIgnorableField(AnnotatedField)
        {
            if(annotatedField.hasAnnotation(JsonSpringView.class))
            {
                JsonSpringView jsv = annotatedField.getAnnotation(JsonSpringView.class);
                if(jsv.springRoles() != null)
                {
                    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    if(principal != null && principal instanceof UserDetails)
                    {
                        UserDetails principalUserDetails = (UserDetails) principal;
                        Collection<? extends  GrantedAuthority> authorities = principalUserDetails.getAuthorities();
                        List<String> requiredRoles = Arrays.asList(jsv.springRoles().split(","));
    
                        for(String requiredRole : requiredRoles)
                        {
                            Feature f = new Feature();
                            f.setName(requiredRole);
                            if(authorities.contains(f))
                            // if The Method Have @JsonSpringView Behind it, and Current User has The Required Permission(Feature, Right, ... . Anything You may Name It).
                            return false;
                        }
                        // if The Method Have @JsonSpringView Behind it, but the Current User doesn't have The required Permission(Feature, Right, ... . Anything You may Name It).
                        return true;
                    }
                }
            }
            // if The Method Doesn't Have @JsonSpringView Behind it.
            return false;
        }
    }
    
  3. Jersey服务器的序列化/反序列化默认为ObjectMapper。如果你正在使用这样的系统并且想要更改它的默认ObjectMapper,那么步骤3,4和5是你的,否则你可以阅读这一步,你的工作就在这里完成。

    JsonSpringObjectMapperProvider.java

    @Provider
    public class JsonSpringObjectMapperProvider implements ContextResolver<ObjectMapper>
    {
        ObjectMapper mapper;
    
        public JsonSpringObjectMapperProvider()
        {
            mapper = new ObjectMapper();
            AnnotationIntrospector one = new JsonSpringViewAnnotationIntrospector();
            AnnotationIntrospector two = new JacksonAnnotationIntrospector();
            AnnotationIntrospector three = AnnotationIntrospector.pair(one, two);
    
            mapper.setAnnotationIntrospector(three);
        }
    
        @Override
        public ObjectMapper getContext(Class<?> arg0) {
            return this.mapper;
        }
    }
    
  4. 您应该扩展javax.ws.rs.core.Application并在Web.xml中提及您的类名。我的是RestApplication.Like:

    RestApplication.java

    import java.util.HashSet;
    import java.util.Set;
    
    import javax.ws.rs.core.Application;
    
    public class RestApplication extends Application
    {
        public Set<Class<?>> getClasses() 
        {
            Set<Class<?>> classes = new HashSet<Class<?>>();
            classes.add(JsonSpringObjectMapperProvider.class);
            return classes ;
        }
    }
    
  5. 这是最后一步。你应该在你的web.xml中提到你的Application类(从第4步开始):

    我的web.xml的一部分

    <servlet>
        <servlet-name>RestService</servlet-name>
        <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.package</param-name>
            <param-value>your_restful_resources_package_here</param-value>
        </init-param>
        <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <!-- THIS IS THE PART YOU SHOULD PPPAYYY ATTTTENTTTTION TO-->
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>your_package_name_here.RestApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
  6. 从现在起你只需要提到你想要的任何属性背后的@JsonSpringView注释。像这样:

    PersonDataTransferObject.java

    public class PersonDataTransferObject
    {
        private String name;
    
        @JsonSpringView(springRoles="ADMIN, SUPERUSER")  // Only Admins And Super Users Will See the person National Code in the automatically produced Json.
        private String nationalCode;
    }
    

答案 2 :(得分:2)

虽然可以编写自定义JSON处理过滤器(例如基于JSON Pointers),但这样做有点复杂。

最简单的方法是创建自己的DTO并仅映射用户有权获取的属性。