我正在做一个简单的小grails应用程序,决定使用Shiro注册/安全,我遇到了一个(可能很傻)的问题。
我已经生成了用户(和领域)类,然后将用户扩展为与帖子有一对多的关联(即用户可以编写博客条目)。但是如何从Shiro主题获取域对象呢?
我试过以下几种方法:
def currentUser = SecurityUtils.getSubject()
def posts = Post.findByUser(currentUser)但这给了我:“消息:没有发现能够从org.apache.shiro.web.subject.support.WebDelegatingSubject类型转换为com.lordfoom.challengetrackr.User类型的转换器”。
域类如下:
class User {
String username
String passwordHash
static hasMany = [ roles: Role, permissions: String, posts: Post ]
static constraints = {
username(nullable: false, blank: false, unique: true)
}
}
class Post {
String title;
String body;
static belongsTo = [user:User]
static constraints = {
title(nullable:false, blank: false, unique: true)
user(unique:true)
}
}是否有一种简单的方法从Shiro主题获取当前登录用户的域对象?还是我一定要查一下?
任何帮助都很感激。
发布于 2014-04-07 19:01:36
如果我正确理解了这一点,您只想为当前登录的用户检索用户对象,是吗?
我通常通过设置包含两个方法的UserService来实现这一点。然后,我可以在整个应用程序中实现getLocalUser()。
import org.apache.shiro.SecurityUtils
class UserService {
/**
* for currently logged in user
*/
def getLocalUserId(){
def userName = SecurityUtils.subject?.principal
User.findByUsername(userName)
}
User getLocalUser(){
getLocalUserId()
}
}希望这能有所帮助。
https://stackoverflow.com/questions/22918311
复制相似问题