【问题标题】:Displaying a property of a Spring Security class in Grails在 Grails 中显示 Spring Security 类的属性
【发布时间】:2014-01-21 20:39:39
【问题描述】:

这是我的用户类,上面有 Spring Security

package rms

import java.util.Date;
import java.util.Set;

import enums.EmployeeStatus;

class User {

   transient springSecurityService

   String username
   String password
   boolean enabled
   boolean accountExpired
   boolean accountLocked
   boolean passwordExpired


   String firstName
   String lastName
   String middleName
   String contactNumber
   String position
   String emailAddress
   String employeeID
   Date dateOfBirth
   EmployeeStatus employeeStatus
   int age
   byte [] picture

   static hasMany = [employeeReport: EmployeeReport]

   static constraints = {
      picture maxSize:20* 1024 * 1024
      dateOfBirth nullable: true
      employeeStatus blank: false
      position blank: false
      contactNumber blank: false
      emailAddress blank: false, matches: "([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})", email: true
      age min: 18

      username blank: false, unique: true
      password blank: false, password: true
   }

   static mapping = { password column: '`password`' }

   Set<SecRole> getAuthorities() {
      SecUserSecRole.findAllBySecUser(this).collect { it.secRole } as Set
   }

   def beforeInsert() {
      encodePassword()
   }

   def beforeUpdate() {
      if (isDirty('password')) {
         encodePassword()
      }
   }

   protected void encodePassword() {
      password = springSecurityService.encodePassword(password)
   }

   String toString(){
      return "SecUser $username"
   }
}

我试过这个标签&lt;sec:loggedInUserInfo field="username"/&gt;,它工作正常,但这不起作用&lt;sec:loggedInUserInfo field="firstName"/&gt;。它给出了一个

没有这样的属性:类的名字:org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser

有没有其他方法可以显示当前登录用户的其他属性?

【问题讨论】:

  • &lt;sec:loggedInUserInfo field="username"/&gt; 用于 Spring Security 定义的字段,如用户名、启用等,而不用于开发人员定义的其他字段。

标签: grails spring-security


【解决方案1】:

loggedInUserInfo 只能访问来自“主体”的数据,该主体通常是GrailsUser 的一个实例。数据包括用户名、id、分配的角色名称,以及一些关于用户是否启用、帐户是否被锁定等的布尔值。很容易继承 GrailsUser 并创建自己的 UserDetailsService 并从身份验证期间的用户域类,并将其存储在GrailsUser 子类中以使其可用于此标记;请参阅http://grails-plugins.github.io/grails-spring-security-core/docs/manual.1273/guide/11%20Custom%20UserDetailsService.html 了解更多信息。

如果数据是只读的,这很有效,因为它将被缓存直到用户注销或会话到期。如果您要显示的数据可以更改,请检索用户实例并将其添加到您从控制器操作返回的模型映射中:

class MyController {

   def springSecurityService

   def theAction() {
       ...
       def user = springSecurityService.currentUser
       [user: user, foo: 5, bar: "whatever", ...]
   }
}

然后您可以在 GSP 中显示您想要的任何内容,例如${user.firstName}

【讨论】:

    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 2011-11-25
    • 2021-06-26
    • 2013-08-29
    • 2013-05-03
    • 2012-09-09
    • 2012-12-25
    • 2016-01-13
    相关资源
    最近更新 更多