[英]Get to the grails domain object from the Shiro Subject
I'm doing a simple little grails app and decided on Shiro for signup/security and I've run into a (probably silly) problem. 我正在做一个简单的小grails应用程序,并决定使用Shiro进行注册/安全,但遇到了一个(可能很愚蠢的)问题。
I've generated the User (and Realm) class, and then extended the User to have a one-to-many association with Posts (ie the User can write, eg, blog entries, is the idea). 我生成了User(和Realm)类,然后将User扩展为与Posts具有一对多关联(即,用户可以编写例如博客条目)。 But how do I get the Domain object from the Shiro subject? 但是,如何从Shiro主题获取Domain对象?
I've tried the following: 我尝试了以下方法:
def currentUser = SecurityUtils.getSubject()
def posts = Post.findByUser(currentUser)
But that gives me: "Message: No converter found capable of converting from type org.apache.shiro.web.subject.support.WebDelegatingSubject to type com.lordfoom.challengetrackr.User" 但这给了我:“消息:找不到能够将org.apache.shiro.web.subject.support.WebDelegatingSubject类型转换为com.lordfoom.challengetrackr.User类型的转换器”
The domain classes are as follows: 域类如下:
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)
}
}
Is there a simple way to get from the Shiro Subject to the currently logged in user's domain object? 有没有简单的方法可以从Shiro主题获取当前登录的用户的域对象? Or do I have to look it up somehow? 还是我必须以某种方式查找它?
Any help appreciated. 任何帮助表示赞赏。
If I am understanding this correctly, you just want to retrieve the user object for the user who is currently signed in, yes? 如果我正确地理解了这一点,那么您只想为当前登录的用户检索用户对象,是吗?
The way that I usually achieve this is by setting up a UserService containing two methods. 我通常实现此目的的方法是设置包含两个方法的UserService。 Then I can implement getLocalUser() throughout the application. 然后,我可以在整个应用程序中实现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()
}
}
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.