grails - 如何在 GSP 中使用 Spring Security Grails 插件获取 current_user

标签 grails spring-security grails-2.0 gsp

我是 Grails 的新手。我正在使用 Spring Security Grails plugin用于身份验证。我想在我的 View gsp 文件中获取当前用户。

我正在尝试这样......

<g:if test="${post.author == Person.get(springSecurityService.principal.id).id }">
      <g:link controller="post" action="edit" id="${post.id}">
            Edit this post
      </g:link>
</g:if>

这里我要展示编辑此帖 仅链接到由登录用户创建的帖子。但它显示错误 -
Error 500: Internal Server Error

 URI
    /groovypublish/post/list
 Class
   java.lang.NullPointerException
 Message
   Cannot get property 'principal' on null object

这是我的 Post.groovy --
class Post {

static hasMany = [comments:Comment]

String title
String teaser
String content
Date lastUpdated
Boolean published = false
SortedSet comments
Person author

....... more code ....

这是我的 Person.groovy 域类文件——
class Person {

transient springSecurityService

String realName
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
byte[] avatar
String avatarType

static hasMany = [followed:Person, posts:Post]
static searchable = [only: 'realName']
    ........ more code ......

请帮忙。

最佳答案

您可以使用 Spring Security Taglibs .对于您想要做什么,请检查登录用户是否是帖子的所有者,您可以执行以下操作:

<sec:isLoggedIn>
<g:if test="${post.author.id == sec.loggedInUserInfo(field: 'id')}">
      <g:link controller="post" action="edit" id="${post.id}">
            Edit this post
      </g:link>
</g:if>
</sec:isLoggedIn>

如果您发现需要经常进行此检查,我建议将其放入自定义标签库中
class AuthTagLib {

  def springSecurityService

  def isOwner = { attrs, body ->
    def loggedInUser = springSecurityService.currentUser
    def owner = attrs?.owner

    if(loggedInUser?.id == owner?.id) {
      out << body()
    }
  }
}

然后像这样使用它
<g:isOwner owner="${post?.author}">
  <g:link controller="post" action="edit" id="${post.id}">
    Edit this post
  </g:link>
</g:isOwner>

关于grails - 如何在 GSP 中使用 Spring Security Grails 插件获取 current_user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17526402/

相关文章:

grails - Grails看不到axis-1.4.jar

grails - 在 GORM 中重命名复合外键

Spring Security 用户名密码AuthenticationFilter : How to access Request after a failed login

grails - Grails 中的 lib 目录

plugins - Grails - 卸载 Spring Security Core

grails - 部署时,空对象上的Grails多部分表单服务器500错误,但不在本地主机上

java - 带有自定义 AngularJS 登录页面的 Spring Boot 和安全性

java - 将 Tomcat 配置为更喜欢一个签名者而不是另一个签名者或者每个端点使用不同的证书?

grails - grails 中的编码和解码如何使用grails 中的decodeHTML 和encodeAsHTML 进行?

grails - grails从自动完成字段的值获取ID