package util;
import java.util.Set;
import model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.UserManager;
public class DBRealm extends AuthorizingRealm {
private static final Logger log = LoggerFactory.getLogger(DBRealm.class);
private UserManager userManager;
public void setUserManager(UserManager userManager) {
log.debug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
this.userManager = userManager;
}
/**
* 根据用户名查某个人的权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.fromRealm(getName()).iterator().next();
Set<String> stringPermissions = userManager.getPermission(username);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(stringPermissions);
return info;
}
/**
* 认证有没有这个人
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
String username = token.getUsername();
char[] password = token.getPassword();
String pwd = password != null ? new String(password) : null;
User user = userManager.loadUser(username, pwd);
if (user != null) {
return new SimpleAuthenticationInfo(username, pwd, getName());
} else {
return null;
}
}
}