【问题标题】:Grails: User evaluator for Commentable with Spring Security pluginGrails:带有 Spring Security 插件的 Commentable 用户评估器
【发布时间】:2011-04-02 06:03:52
【问题描述】:

我正在尝试将可注释插件与 Spring Security 一起使用。

我写不出来

grails.commentable.poster.evaluator

我试过 {User.get(springSecurityService.principal.id)}, 但从 CommentController 来看,User 和 springSecurity 似乎都无法访问。

我该怎么办?

【问题讨论】:

    标签: grails spring-security


    【解决方案1】:

    对于springSecurityService.principal.id,因为springSecurityService 没有依赖注入字段,所以它不能工作,所以你需要调用springSecurityService.principal.id 调用的内容 - org.springframework.security.core.context.SecurityContextHolder.context.authentication.principal.id

    要解决 User 的问题,您需要带有 package.json 的完整类名。这么结合,应该是这样的

    {com.yourcompany.yourapp.User.get(org.springframework.security.core.context.SecurityContextHolder.context.authentication.principal.id)}
    

    【讨论】:

    • 非常感谢您的帮助和非常快速的答复。同时,我编写了一个小插件,为每个控制器添加了一个 getCurrentUser。然后我在评估器中使用 currentUser 。它似乎工作这是一个坏主意吗? (我是 Groovy 和 Grails 的新手,所以不知道添加这种方法是否是反习惯用法)
    • 这提醒了我Spring Security Core已经添加了一个getPrincipal()方法,这样可以缩短对com.yourcompany.yourapp.User.get(principal.id)的调用,但最好还有一个getCurrentUser方法-我会在下一个版本中添加它。
    【解决方案2】:

    我调整了Burt's answer,这样它就不会在没有人登录时抛出异常

    grails.commentable.poster.evaluator = {
    
        def principal = org.springframework.security.core.context.SecurityContextHolder.context.authentication?.principal
    
        if (principal?.hasProperty('id')) {
    
            def currentUserId = principal.id
            if (currentUserId) {
                com.yourcompany.yourapp.User.get(currentUserId)
            }
        }
    }
    

    【讨论】:

    • 谢谢,这也适用于 rateable 插件。 ...但是当没有用户登录时它仍然抛出异常。即未定义 [grails.rateable.rater.evaluator] 设置或评估器不评估实体
    • @10ToedSloth 谢谢,我已经解决了这个问题(4 年后)
    猜你喜欢
    • 2016-08-30
    • 2016-05-24
    • 2011-12-06
    • 2011-08-15
    • 2016-03-23
    • 2012-09-29
    • 2017-05-26
    • 2014-07-30
    • 2016-08-16
    相关资源
    最近更新 更多