这个问题的解决方案非常简单。我为杰克逊创建了一组视图类:
public class SecureViews {
public static class Public{};
public static class Authenticated extends Public{};
public static class User extends Authenticated{};
public static class Internal extends User {};
}
然后,我通过添加以下内容为我想要保护的每个实体注释了所有 getter 方法:
@JsonView(SecureViews.Authenticated.class)
public String getPhoneNumber() {
return phoneNumber;
}
上述规则的意思是,只有在系统内通过身份验证的用户才能查看用户的电话号码。
或者
@JsonView(SecureViews.User.class)
public List<Event> getEvents() {
return Collections.unmodifiableList(events);
}
然后我创建了一个接口并在我的所有安全实体中实现了该接口:
public interface SecurePropertyInterface {
Class<?> getMaxPermissionLevel(Long userID);
}
这是该方法的实现:
public Class<?> getMaxPermissionLevel(Long userID) {
if (userID != null && userID == uid) {
return SecureViews.User.class;
}
if (SecurityUtils.getSubject().isAuthenticated()) {
return SecureViews.Authenticated.class;
}
return SecureViews.Public.class;
}
现在来说说魔法。扩展MappingJacksonJsonView
并覆盖以下方法:
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Long userID = CTConversionUtils.convertToLong(request.getParameter("id"));
model = (Map<String, Object>) super.filterModel(model);
Class<?> viewClass = SecureViews.Public.class;
if(SecurityUtils.getSubject().isAuthenticated()) {
viewClass = SecureViews.Authenticated.class;
}
for (Entry<String, Object> modelEntry : model.entrySet()) {
if (modelEntry.getValue() instanceof SecurePropertyInterface) {
viewClass = ((SecurePropertyInterface)modelEntry.getValue()).getMaxPermissionLevel(userID);
}
}
objectMapper.viewWriter(viewClass).writeValue(getJsonGenerator(response), model);
}
您还可以setObjectMapper
在 Spring 设置您的MappingJacksonJsonView
.
我的 Spring 配置如下所示:
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
p:order="1">
<property name="mediaTypes">
<map>
<entry key="json" value="*/*" />
</map>
</property>
<property name="defaultViews">
<list>
<bean
class="com.bytesizecreations.connecttext.json.SecureMappingJacksonJsonView">
<property name="objectMapper">
<bean
class="org.codehaus.jackson.map.ObjectMapper" />
</property>
</bean>
</list>
</property>
</bean>
那么我们现在在这里有什么?每次需要将响应反序列化为 JSON 时,都会调用 renderMergedOutputModel 方法。如果用户的 id 在我们存储的请求中。然后我们可以遍历模型映射并检查每个值是否是 SecurePropertyInterface 以及是否获得其最大权限级别。
这个策略似乎很适合我的目的。当用户请求用户列表时,他们只会获得经过身份验证的属性,但当用户请求他们自己的详细信息时,他们只会获得他们的私有属性。
我怀疑这段代码可以进一步改进,但我花了太多时间试图让它不那么复杂。