Question

I'm doing a simple little grails app and decided on Shiro for signup/security and I've run into a (probably silly) problem.

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). But how do I get the Domain object from the Shiro subject?

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"

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? Or do I have to look it up somehow?

Any help appreciated.

Was it helpful?

Solution

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. Then I can implement getLocalUser() throughout the application.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top