我是 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/