首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Security @Security用于验证控制器

Security @Security用于验证控制器
EN

Stack Overflow用户
提问于 2019-02-04 18:10:34
回答 2查看 558关注 0票数 0

我的控制器中有以下方法。

代码语言:javascript
运行
复制
    @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";
    }

这是用于更新exist帖子的表单。

我希望限制只发布这个帖子的用户的访问权限。这样随机用户就无法访问。

所以我试过这个..。为了通信,当前用户的电子邮件(authentication.name)与邮件的所有者的电子邮件。但没有运气。

代码语言:javascript
运行
复制
    @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参数有一个空值。这一点很明显,因为它是在中定义的方法。(或者我使用它的方式完全错误。)

你知道我在做什么吗?为此,我如何使用预授权?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-05 18:40:25

我用RequestParam解决了这个问题。

代码语言:javascript
运行
复制
    @PreAuthorize("#userid == #user.id")
    @GetMapping("/update/{idpost}")
    public String showUpdateForm(
            @PathVariable int idpost, 
            @ModelAttribute("post") Post post,
            @ModelAttribute("user") User user,
            @RequestParam("u") int userid,
            Model model) {

        post = postService.findById(idpost);
        model.addAttribute("post", post);
        return "_updateForm";
    }

请求可能是这样的。

代码语言:javascript
运行
复制
http://localhost:8080/...../update/31?u=83
票数 0
EN

Stack Overflow用户

发布于 2019-02-04 21:27:35

我认为PostAuthorize是你想要的。注意:我自己也没有使用过这个注释,但这就是它所暗示的。如果这对你来说还不够的话,让我知道,我可以多做一些调查,看看能不能给你一个样本。

PS。不要忘记启用PostAuthorize @EnableGlobalMethodSecurity(prePostEnabled = true)

代码语言:javascript
运行
复制
    @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";
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54521960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档