首页 > 解决方案 > 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?

标签: javaspring-mvcspring-security

解决方案


我想这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";
    }

推荐阅读