我建议您使用spring-security
自定义PermissionEvaluator
,这样您基本上可以在网页和控制器中使用相同的实现:
在您可以使用的网页中:
<security:authorize access="hasPermission(#shop,'see')"></security:authorize>
在您的控制器和您可以使用的任何服务方法中:
@PreAuthorize("hasPermission(#shop,'see')")
像这样:
@PreAuthorize("hasPermission(#shop,'see')")
@RequestMapping("/someUrl")
public String processSomeUrl(@ModelAttribute("shop") Shop shop){
shop.getStuff();
}
或也@PostAuthorize
和@PostFilter("hasPermission(filterObject,'see')")
(过滤列表)
所有这些功能将根据您自己的权限评估者限制访问或过滤结果列表。它们都将指向相同的实现,看起来像这样:
@Component
public class MyPermissionEvaluator implements PermissionEvaluator {
private final Log logger = LogFactory.getLog(getClass());
@Override
public boolean hasPermission(Authentication auth, Object arg1, Object arg2) {
logger.info("hasPermission "+auth+" - "+arg1+" - "+arg2+" ");
if(arg2 instanceof String && arg1 instanceof Shop){
Shop shop = (Shop)arg1;
if(((String) arg2).equals("see")){
//here you can have your own function
boolean result = hasPermissionSeeShop(auth, project);
return result;
}
}
return false;
}
@Override
public boolean hasPermission(Authentication arg0, Serializable arg1,
String arg2, Object arg3) {
logger.info("hasPermission "+arg0+" - "+arg1+" - "+arg2+" - "+arg3+" ");
return false;
}
}
此外,当这些方法返回 false 时,它会自动抛出 AccessDeniedException,您可以轻松地将其配置为在 http 元素中重定向到您自己的 accessDenied 页面:
<http auto-config="true">
<intercept-url pattern="/admin*" access="ROLE_ADMIN" />
<access-denied-handler error-page="accessDeniedPage"/>
</http>