0

我正在使用 Spring MVC 开发一个小型应用程序。这是一种广告牌,用户可以在其中放置多种类型的内容。我已经使用 security-config.xml 成功地为我的应用程序(用户、管理员、匿名)中的不同角色配置了安全性。现在您必须登录才能发帖,只有管理员用户才能看到管理面板等。

现在我的问题是我必须为每个用户设置安全性,即修改内容的用户是制作内容的用户。如果登录的用户和内容的创建者都相同,最直接的方法当然是在我调用我的函数之前检查 Java。像这样的东西:

@RequestMapping("/listing/deletecontent.html")
public String deleteUserContent(@RequestParam String contentId) {
    //Get the logged user
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User user = userService.loadUserByUsername(userDetails.getUsername());

    //Check if the user logged and the content owner are the same
    if (user == the_user_that_created_the_content)
          listingService.deleteContent(Integer.valueOf(contentId));

    return "redirect:/listing/usercontent.html";
}

我不知道为什么,但我不喜欢这种方法。它只是在我需要的地方一遍又一遍地“复制粘贴”相同的验证,而且感觉不对。我在想也许 Spring 具有某种类型的功能,允许我在 security-config.xml 中进行设置,也许调用一个类来使用contentId参数对每个 URL 进行此验证,然后将其重定向到“真实”URL,如果它通过了测试。我不知道,这就是我想问你的。¿ 您如何看待这种方法?¿ 可能是我太挑剔了,没那么糟糕?¿您知道“更好”的方法吗?

提前非常感谢,詹姆

4

1 回答 1

0

我建议仔细查看Spring Security 参考中基于表达式的访问控制章节。所以,据我所知,你不应该自己检查权限——只需使用@PreAuthorize注释。尝试 ACL 模块,或者如果它不符合您的要求,可能更好地实现 custom PermissionEvaluator

PS还有这样的事情: @PreAuthorize("principal.id == #content.createdBy.id")

于 2012-08-01T20:26:29.300 回答