【问题标题】:Spring Security Service with Grails - Get current user 'NULL' error带有 Grails 的 Spring Security Service - 获取当前用户“NULL”错误
【发布时间】:2018-02-13 11:32:09
【问题描述】:

您好,我正在尝试使用 Grails 的 Spring Security Core 并尝试获取当前登录的用户。但是,我得到 java.lang.NullPointerException,这是由以下原因引起的:Cannot get property 'principal' on null object。

以下是我的代码:

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
import grails.plugin.springsecurity.annotation.Secured

@Secured(['ROLE_ADMIN'])
@Transactional
class MyController {

    static allowedMethods = [save: "POST", update: "PUT", delete: 
                            "DELETE"]

    def test(){
         def springSecurityService
         render "Current User is: [" + springSecurityService.principal  
                                  + "]"
         }
    }

由于某些原因 springSecurityService 为空。我错过了什么?

请指教。提前谢谢!

【问题讨论】:

  • def springSecurityService 应该在类级别的方法 test() 之外。
  • 非常感谢约书亚!这行得通!真的很感激!
  • 当你把它放在类级别时,你实际上是在你的控制器 bean 类中注入一个 spring 服务 bean,它与 spring autowired 等效/相同。但在方法内部它只是一个变量。
  • 谢谢妈妈!欣赏解释!

标签: grails spring-security


【解决方案1】:

正如 Joshua Moore 所建议的那样,这很有效!非常感谢!

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
import grails.plugin.springsecurity.annotation.Secured

@Secured(['ROLE_ADMIN'])
@Transactional
class MyController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    def test(){



        render "Current User is: [" + springSecurityService.principal  + "]"


    }

}

【讨论】:

    猜你喜欢
    • 2014-06-10
    • 2014-03-31
    • 2017-03-20
    • 2014-08-08
    • 2020-02-12
    • 1970-01-01
    • 2013-11-29
    • 2011-10-02
    • 2014-07-29
    相关资源
    最近更新 更多