Spring 3.2:根据Spring Security角色过滤Jackson JSON输出 [英] Spring 3.2: Filtering Jackson JSON output based on Spring Security role
问题描述
有没有什么好的方法可以根据Spring Security角色过滤JSON输出?我正在寻找像@JsonIgnore这样的东西,但是对于角色,比如@HasRole(ROLE_ADMIN)。我应该如何实现这个?
Is there any good way to filter JSON output based on Spring Security roles? I'm looking for something like @JsonIgnore, but for role, like @HasRole("ROLE_ADMIN"). How should I implement this?
推荐答案
对于那些从Google登陆的人来说,这里有一个与Spring Boot 1.4类似的解决方案。
For those landing here from Google, here is a similar solution with Spring Boot 1.4.
为每个角色定义接口,例如
Define interfaces for each of your roles, e.g.
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
,例如
Declare @JsonView
in your entities, e.g.
@Entity
public class SomeEntity {
@JsonView(View.Anonymous.class)
String anonymousField;
@JsonView(View.BusinessAdmin.class)
String adminField;
}
并定义 @ControllerAdvice
根据角色选择正确的 JsonView
:
And define a @ControllerAdvice
to pick up the right JsonView
based on the roles:
@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);
}
}
这篇关于Spring 3.2:根据Spring Security角色过滤Jackson JSON输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!