第十讲 shiro 与SSM的集成(3)写自己的认证类MyRealm

时间:2022-02-07 14:27:41
MyRealm类的内容如下:

------------------------------

package com.vv.shiro;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Resource;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.vv.UserService.UserService;
import com.vv.dao.UserDao;
import com.vv.pojo.User;
public class MyRealm extends AuthorizingRealm{
    @Autowired
    private UserDao userdao;

    /**
     *验证当前登录的用户
     */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
//获取你输入的用户账号
        String username = token.getPrincipal().toString() ;
        //在数据库中去查找你的用户信息
        User user = userdao.findUserByUserName(username) ;
        if (user != null){
            //将查询到的用户账号和密码存放到 authenticationInfo用于后面的权限判断。第三个参数传入realName。
        System.out.println("数据库中账号"+user.getUsername());
        System.out.println("数据库中密码"+user.getPassword());
            AuthenticationInfo authenticationInfo =
            new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),"a") ;
            System.out.println("成功了吗?");
            return authenticationInfo ;
        }else{
            return  null ;
        }
}
    
    /**
     * 为当前登录的用户授予角色和权限
     * shiro什么时候会进入doGetAuthorizationInfo?
     * 1、subject.hasRole(“admin”) 或 subject.isPermitted(“admin”):自己去调用这个是否有什么角色或者是否有什么权限的时候;
     * 2、@RequiresRoles("admin") :在方法上加注解的时候;
     * 3、[@shiro.hasPermission name = "admin"][/@shiro.hasPermission]:在页面上加shiro标签的时候,
     * 即进这个页面的时候扫描到有这个标签的时候。
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String username = principals.getPrimaryPrincipal().toString() ;
    System.out.println("授权了"+username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo() ;
        Set<String> roleName = userdao.findRoles(username) ;
        //在这里输出roleName信息
        Iterator it=roleName.iterator();
        while(it.hasNext()){
            System.out.println("角色有:"+it.next());
        }
        Set<String> permissions = userdao.findPermissions(username) ;
        //在这里输出permissions信息
        Iterator pt =permissions.iterator();
        while(pt.hasNext()){
            System.out.println("权限有:"+pt.next());
        }        
        info.setRoles(roleName);
        info.setStringPermissions(permissions);
        return info;
    }
}