我想使用 @PreAuthorize Spring 注释来控制我的应用程序中的访问。
问题是,我有很多条件不是取决于请求参数,而是取决于数据库实体。
概述:
我有一个Route
实体,它有User owner
字段。Route
仅当您是所有者时才能删除。
我写了我的控制器方法:
@RequestMapping(value = "/route/remove/{id}", method = RequestMethod.GET)
@PreAuthorize("hasPermission(#id, 'RouteRemove')")
public String removeRoute(@PathVariable("id") Integer id, ModelMap model) {
Route route = routeBO.getById(id);
if(null == route)
return "forward:/errors/404";
// ... remove route here.
// routeBO.remove(id);
}
我的RouteRemove
权限定义为:
@Component
public class RouteRemovePermission implements Permission {
@Autowired
private RouteBO routeBO;
@Override
public boolean isAllowed(Authentication authentication, Object targetDomainObject) {
if(!(targetDomainObject instanceof Integer))
return false;
Route route = routeBO.getById((Integer) targetDomainObject);
if(route == null)
return false;
User user = AthenticationUtil.getUser();
return null != user && user.equals(route.getOwner());
}
}
如您所见,我必须评估routeBO.getById()
两次。
问题:
是否可以只评估此代码一次?
我当然试过:
@RequestMapping(value = "/route/remove/{id}", method = RequestMethod.GET)
public String removeRoute(@PathVariable("id") Integer id, ModelMap model) {
Route route = routeBO.getById(id);
if(null == route)
return "forward:/errors/404";
return removeRoute(route, model);
}
@PreAuthorize("hasPermission(#id, 'RouteRemove')")
public String removeRoute(Route id, ModelMap model) {
return "route/display";
}
但之前没有调用权限方法removeRoute(Route id, ModelMap model)
。也许我的配置不正确?
mvc-调度程序-servlet.xml
<sec:global-method-security secured-annotations="enabled" pre-post-annotations="enabled">
<sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>
安全.xml
<beans:bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<beans:property name="permissionEvaluator" ref="permissionEvaluator"/>
</beans:bean>
<beans:bean id="permissionEvaluator" class="pl.wsiadamy.common.security.BasePermissionEvaluator">
<beans:constructor-arg index="0">
<beans:map key-type="java.lang.String"
value-type="pl.wsiadamy.common.security.Permission">
<beans:entry key="RouteView" value-ref="routeViewPermission" />
<beans:entry key="RouteRemove" value-ref="routeRemovePermission" />
</beans:map>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="routeViewPermission" class="pl.wsiadamy.common.security.permission.RouteViewPermission" />
<beans:bean id="routeRemovePermission" class="pl.wsiadamy.common.security.permission.RouteRemovePermission" />