我想基于身份验证甚至角色过滤对象属性。 因此,例如,将为经过身份验证的用户返回完整的用户配置文件,并为未经过身份验证的用户过滤
如何使用MappingJacksonHttpMessageConverter
实现目标?我已经为Jaskon声明了自定义bean:
<bean id="objectMapper" class="com.example.CustomObjectMapper"/>
<bean id="MappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="order" value="1" />
<!-- <property name="customArgumentResolver" ref="sessionParamResolver"/> -->
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<!-- <property name="conversionService" ref="conversionService" /> -->
<!-- <property name="validator" ref="validator" /> -->
</bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<ref bean="MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
注意:在控制器中,我将结果写为:
public void writeJson (Object jsonBean, HttpServletResponse response) {
MediaType jsonMimeType = MediaType.APPLICATION_JSON;
if (jsonConverter.canWrite(jsonBean.getClass(), jsonMimeType)) {
try {
jsonConverter.write(jsonBean, jsonMimeType, new ServletServerHttpResponse(response));
} catch (IOException m_Ioe) {
} catch (HttpMessageNotWritableException p_Nwe) {
} catch (Exception e) {
e.printStackTrace();
}
} else {
log.info("json Converter cant write class " +jsonBean.getClass() );
}
}
答案 0 :(得分:0)
如果您想要返回两种不同类型的JSON对象(例如fullProfile
和partialProfile
),那么最好使用两个不同的网址制作两种不同的服务。然后,您可以使用Spring Security的intercept-url标记以正常方式控制对这些网址的访问。
答案 1 :(得分:0)
我在这里完成了大部分工作https://stackoverflow.com/a/39168090/6761668
您需要做的就是遵守自己的安全规则,可能会注入当前用户,并根据他们的角色决定包含或不包含的内容。我在实体列上使用了注释:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Set;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyRestricted {
String[] permittedRoles() default {};
}
该栏看起来像这样:
@Column(name = "DISCOUNT_RATE", columnDefinition = "decimal", precision = 7, scale = 2)
@MyRestricted(permittedRoles = { "accountsAdmin", "accountsSuperUser" })
private BigDecimal discountRate;
规则看起来像这样:
final MyRestricted roleRestrictedProperty = pWriter.findAnnotation(MyRestricted.class);
if (roleRestrictedProperty == null) {
// public item
super.serializeAsField(pPojo, pJgen, pProvider, pWriter);
return;
}
// restricted - are we in role?
if (permittedRoles.contains(myRole)) {
super.serializeAsField(pPojo, pJgen, pProvider, pWriter);
return;
}
// Its a restricted item for ME
pWriter.serializeAsOmittedField(pPojo, pJgen, pProvider);