我正在做一个基于浏览器的游戏。 假设我有一个 Spring Controller ,有很多 Controller ~10。每个都有大约 10 个 url 映射。大约有 100 多种映射方法。
如果满足某些规则,每个映射只会加载或显示正确的内容。将通过执行数据库查询来检查规则。 例如:
我是 12 级用户,只有当用户级别为 10+、20+、30+、40+、50+ 等时,每个 Controller 才允许显示内容。
我可以通过在每个 Controller 中的每个映射方法下进行查询来做到这一点,但是boilerplating太多了。
有没有办法以某种方式集中化,比如将我的限制映射放在一起,而不必将其放在每个 url 映射方法下?
即使设计上可能没有这样的事情,也许您自己也遇到过同样的问题并想出了一些聪明的解决方案?
最佳答案
我建议您使用spring-security
与定制PermissionEvaluator
所以你基本上可以在网页和 Controller 中使用相同的实现:
在网页中您可以使用:
<security:authorize access="hasPermission(#shop,'see')"></security:authorize>
在您的 Controller 和您可以使用的任何服务方法中:
@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>
关于java - 如何为 Spring MVC Controller 创建通用权限管理系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13922706/