我正在尝试使用 spring mvc 3.2.3 和 spring security 3.1.3 创建一个通用 Controller 。 我想要实现的是这样的:
public abstract class DataController<E extends PersistentEntity> {
protected abstract E getEntity(String id);
@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
public String view(@PathVariable("id") String id, ModelMap map) {
E ent = getEntity(id);
map.put("entity", entity);
return "showEntity";
}
}
我的扩展类将在类名中有一个特定的 Controller 映射,这样我就可以使用 Controller 名访问 url:
@Controller
@RequestMapping("/company**")
@Secured("ROLE_ADMIN")
public class CompaniesController extends DataController<Company> {
@Autowired
private AppService appService;
@Override
protected Company getEntity(String id) {
return appService.getCompany(id);
}
}
我的问题是 url/company/view 不受 ROLE_ADMIN 保护,任何人都可以访问(我认为),因为/view 未在使用 @Secured 的 Controller 中定义。
这可以通过覆盖 View 方法并在我的公司类中定义映射来解决:
. . .
@Override
@RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
public String view(String id, ModelMap map) {
return super.view(id, map);
}
. . .
在这种情况下安全工作正常,但我想知道是否有其他方法。因为我的抽象类中有很多方法,这会产生一个问题和困惑来覆盖所有方法只是为了调用 super。
有办法解决这个问题吗?
感谢大家的帮助:)
最佳答案
我知道这是一年后的事了,但我遇到了同样的问题并想出了一个可能的解决方案。它不是 100% 基于注释,但可以工作并且有点优雅
抽象父类(super class):
@PreAuthorize("hasAnyRole(this.roles)")
public abstract class DataController<E extends PersistentEntity>
{
protected abstract E getEntity(String id);
protected abstract String[] getRoles();
@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
public String view(@PathVariable("id") String id, ModelMap map) {
E ent = getEntity(id);
map.put("entity", entity);
return "showEntity";
}
}
在子类上,您只需实现 getRoles()
即可返回访问此类所需的角色数组。
@PreAuthorize
是另一种检查身份验证的方法,它允许您使用 SpEL 表达式。 this.roles
引用注释对象的 getRoles()
属性。
关于java - 具有 Spring Security 的 Spring MVC Controller 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17721523/