Grails - ShiroSecurity - 手动登录用户

时间:2011-08-24 01:23:52

标签: grails shiro

我正在尝试做一些相对简单的事情:手动登录用户。我正在使用FacebookGraph插件连接到Facebook。如果用户通过Facebook登录,我会获得他的身份证,我想在ShiroSecurity中对他进行身份验证。当然像

这样的琐碎事情
session.user = user

不起作用。 我在wiki中找到了代码,应该可以解决这个问题:

Object userIdentity = user.email
String realmName = "username";
PrincipalCollection principals = new SimplePrincipalCollection(userIdentity, realmName);
Subject subject = new Subject.Builder().principals(principals).buildSubject();

然而它不起作用。我仍然使用log.debug消息重定向到auth / login,即ShiroSubject为null。也许是因为我在服务中调用了这段代码。 任何想法如何使这项工作?

更新:

 def authenticate(authToken) {
    log.info "Attempting to authenticate ${authToken.username} in DB realm..."+authToken.encodeAsJSON()
    def username = authToken.username

    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.")
    }

    // Get the user with the given username. If the user is not
    // found, then they don't have an account and we throw an
    // exception.
    log.debug "reached this point2"
    def user = ShiroUser.findByUsername(username)
    log.debug "reached this point"
    if (!user) {
        throw new UnknownAccountException("No account found for user [${username}]")
    }

    log.info "Found user '${user.username}' in DB"

    // Now check the user's password against the hashed value stored
    // in the database.
    def account = new SimpleAccount(username, user.passwordHash, "ShiroDbRealm")
    if (!credentialMatcher.doCredentialsMatch(authToken, account)) {
        log.info "Invalid password (DB realm)"
        throw new IncorrectCredentialsException("Invalid password for user '${username}'")
    }

    return account
}

2 个答案:

答案 0 :(得分:3)

看看AuthController.groovy - > signIn行动。

这正是您需要登录的代码。主要步骤是

SecurityUtils.subject.login(new UsernamePasswordToken(username,password))

希望有帮助...

确定。这只是一个起点...在/Realms上查看您的Realm-Code。你会发现authenticate(authToken)关闭。似乎通过SecurityUtils.subject.login()调用它并处理凭据检查...

这可以用散列密码来解决你的问题......

答案 1 :(得分:2)

根据Javadoc,Subject.Builder()不会自动将主题绑定到当前应用程序线程。在构建Subject实例后尝试添加它:

ThreadContext.bind(subject)