shiro-realm认证

        在前面我们已经提到过,在shiro的认证过程中,我们是将用户名和密码都配置到配置文件中。但是这样会极大的不方面我们的开发,比如说我们要添加或者修改个用户,还得去配置文件中修改,得在重新发布程序,非常的麻烦。不过在shiro中,不用在担心这个问题了,因为它已经给我们提供了一个和数据库交互的功能。这就是realm。下面来看下面的实例:

1、新建Realm

/**
 * 自定义realm
 * @author liujie
 *
 */
public class CustomRealm extends AuthorizingRealm {
    //设置realm的名称
    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }
    
    //用于授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    //用于认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        // token是用户输入的
        //第一步从token中取出身份信息
        String userCode=(String)token.getPrincipal();
        
//        if (!userCode.equals("zhangsansan")) {
//            return null;
//        }
        //第二步:根据用户输入的userCode从数据库查询
        //。。。。。。
        //模拟从数据库查询到的密码
        String password="1111112";
        
        //如果查询不到返回null
        
        //如果查询到返回认证信息AuthenticationInfo
        
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(
                userCode, password, this.getName());
        
        return simpleAuthenticationInfo;
    }
}

2、告诉shiro应用我们自己定义的Realm

[main]
#自定义realm
customRealm=cn.itcast.shiro.realm.CustomRealm
#将realm设置到securityManager,相当于spring中注入
securityManager.realms=$customRealm  

3、测试我们的功能

public class AuthenticationTest {
    /**
     * 自定义realm
     * 用户登录
     */
    @Test
    public void testCustomRealm(){
        //创建securityManager工厂,通过ini配置文件创建securityManager工厂
        Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro-realm.ini");
        //创建SecurityManager
        SecurityManager securityManager=factory.getInstance();
        //将securityManager设置到当前的运行环境中
        SecurityUtils.setSecurityManager(securityManager);;
        //从SecurityUtils里边创建一个subject
        Subject subject=SecurityUtils.getSubject();
        //在认证提交前准备token(令牌)
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "111111");
        try {
            //执行认证提交
            subject.login(token);
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        //是否认证通过
        boolean isAuthenticated=subject.isAuthenticated();
        
        System.out.println("是否认证通过:"+isAuthenticated);
        
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值