问题
The usual way of authenticating user is to invoke:
SecurityUtils.subject.login(new UsernamePasswordToken(params.username, params.password))
However, what if I would like to log him in automagically, without necessity of typing username and password? I have created method in userService like this:
def logIn(User user){
Object userIdentity = user.email
String realmName = "ShiroDbRealm";
PrincipalCollection principals = new SimplePrincipalCollection(userIdentity, realmName);
Subject subject = new Subject.Builder().principals(principals).buildSubject();
ThreadContext.bind(subject)
}
But this does not work, any hints?
回答1:
I have managed to solve the issue. I have created my own class that implements AuthenticationToken interface:
class UsernameToken implements AuthenticationToken{
private username;
public UsernameToken(String username) {
this.username = username;
}
public String getPrincipal() {
return username;
}
public String getCredentials() {
return username;
}
}
and created new Realm which looks exactly the same as the default one but without password verification. Now I can use
SecurityUtils.subject.login(new UsernameToken(user.username))
来源:https://stackoverflow.com/questions/7687022/grails-shirosecurity-log-in-user-without-usernamepasswordtoken