grails - authenticatedUser 为 null 但原则不为 null

标签 grails spring-security grails-2.0 grails-plugin

Grails 安全新手在这里。我正在浏览文档并尝试了这个。
成功登录后,即使填充了主体,为什么经过身份验证的用户为空。还有什么我需要做的吗?

class SecureController {

 @Secured(['ROLE_ADMIN'])
 def userInfo(){
     if (isLoggedIn()){
      //authenticatedUser is null though user is authenticated.
      render authenticatedUser
      //render principal
    }
 }
}

从文档

获取AuthenticatedUser

Loads the user domain class instance from the database that corresponds to the currently authenticated user, or null if not authenticated. This is the equivalent of adding a dependency injection for springSecurityService and calling PersonDomainClassName.get(springSecurityService.principal.id) (the typical way that this is often done).

最佳答案

您需要在 Controller 中注入(inject) springSecurityService

class SecureController {

 def springSecurityService

 @Secured(['ROLE_ADMIN'])
 def userInfo(){
     if (springSecurityService.isLoggedIn()){
      //authenticatedUser is null though user is authenticated.
      render authenticatedUser
      //render principal
    }
 }
}

您还可以使用 springSecurityService.getCurrentUser() 检查您是否有有效的登录用户并呈现它。 spring security core documentation很清楚,看看吧!

关于grails - authenticatedUser 为 null 但原则不为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25293757/

相关文章:

grails - 运行时出现Grails错误

json - 从 object/json 中删除字段属性

hibernate - Grails和Hibernate的惰性初始化异常

spring - 如何有单独的身份验证源? (一个用于 Oauth2,一个用于基于表单的登录)

grails - Grails 2.2.x中的连接池?

rest - Grails REST 客户端插件 - 指定 header 数据

java - Spring安全@PreAuthorize NullPointerException。为什么?

Spring Security @PreAuthorize - 使用 Spring EL 限制某些角色

grails - grails war命令在打包之前会运行测试吗?

spring - 如何修复 "Invalid remember-me token (Series/token) mismatch"错误?