java - Spring Security @PreAuthorize 用于验证控制器
问题描述
我的控制器中有以下方法。
@GetMapping("/update/{idpost}")
public String showUpdateForm(
@PathVariable int idpost,
@ModelAttribute("post") Post post,
@ModelAttribute("user") User user,
Model model) {
post = postService.findById(idpost);
model.addAttribute("post", post);
return "_updateForm";
}
它正在显示更新现有帖子的表格。
我想限制对仅发布此帖子的用户的访问。这样随机用户将无法访问。
所以我尝试了这个..旨在将当前用户的电子邮件(authentication.name)与帖子所有者的电子邮件相对应。但没有运气。
@PreAuthorize("#post.user.email == authentication.name")
@GetMapping("/update/{idpost}")
public String showUpdateForm(
@PathVariable int idpost,
@ModelAttribute("post") Post post,
@ModelAttribute("user") User user,
Model model) {
post = postService.findById(idpost);
model.addAttribute("post", post);
return "_updateForm";
}
原来,post参数有一个空值。这是显而易见的,因为它在方法中定义。(或者我使用它的方式完全错误。)
你会明白我在做什么吗?我怎样才能为此目的使用@PreAuthorize?
解决方案
我想这PostAuthorize
就是你想要的。注意:我自己没有使用过这个注释,但这就是它所暗示的。如果这对您来说还不够,请告诉我,我可以进行更多调查,看看是否可以为您提供样品。
PS。不要忘记启用 PostAuthorize@EnableGlobalMethodSecurity(prePostEnabled = true)
@PostAuthorize("#returnObject.user.email == authentication.name")
public Post getPost(int idpost) {
return postService.findById(idpost);
}
@GetMapping("/update/{idpost}")
public String showUpdateForm(
@PathVariable int idpost,
@ModelAttribute("user") User user,
Model model) {
post = getPost(idpost);
model.addAttribute("post", post);
return "_updateForm";
}
推荐阅读
- sql - 将数据导入 DB2 数据库时出错
- python - Python:如何使用 3 个数组 x[]、y[]、z[] 在 3D 中应用 polyfit 功能
- dart - 如何对内部和外部地图进行排序?
- ionic-framework - 离子原生推送通知(Firebase X)不显示应用程序是否在后台
- c++ - 是否可以仅取消隐藏基类的特定重载方法
- javascript - Modify the file before it opens and then open it in a new tab
- django - Target WSGI scriptcannot be loaded as Python module
- python - How to install project in git repository correctly in python?
- python - 如何在 Git repo 中处理应用程序密码
- jboss - ORA-12519 TNS: No appropriate service handler found in JBoss 7.2