shiro配置加密

本文详细介绍使用Apache Shiro框架进行用户身份验证的过程,包括配置凭证匹配器、实现AuthorizingRealm类以及编写测试方法来验证登录流程。通过具体代码示例,展示了如何设置散列算法、迭代次数和盐值,以及如何在Subject中执行登录操作。

步骤一------------------------------------------------------------------------------------------------------------------------------

[main]
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
credentialsMatcher.hashIterations=3
#将凭证匹配器设置到realm
myRealm=com.shiro.realm.PasswordRealm
myRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealm

步骤二------------------------------------------------------------------------------------------------------------------------------

实现抽象类方法:AuthorizingRealm

//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取token中的用户名
        String uname = (String)token.getPrincipal();
        if(!"liuliang".equals(uname)) {
            return null;
        }
        String password = "867e199e5da9c4f16defe1245eb8ecdc";

        //Md5Hash test = new Md5Hash("111111","liuliang",3); 参数一:明文密码,参数二:加盐,参数三:散裂次数
        //info对象表示realm登录比对信息
        
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(uname, password, ByteSource.Util.bytes("liuliang"), getName());
        
        return info;
    }

 

步骤三------------------------------------------------------------------------------------------------------------------------------

编写测试方法

@Test
    public void IniPasswordManagerRealm() {
        //创建SecurityManager创建工厂对象
        Factory<SecurityManager> fileshiro = new IniSecurityManagerFactory("classpath:shiro-cryptography.ini");
        //通过工厂对象创建SecurityManager对象
        SecurityManager securityMg =  fileshiro.getInstance();
        
        //将scurityMg绑定到当前对象当中:让系统随时都可以访问SecurityMg对象
        SecurityUtils.setSecurityManager(securityMg);
        
        //创建当前登录的主体
        Subject subject = SecurityUtils.getSubject();
        
        UsernamePasswordToken token = new UsernamePasswordToken("liuliang", "111111");
        //主体登录 
        try {
            subject.login(token);
        } catch (Exception  e) {
            System.out.println("登录失败");
            e.printStackTrace();
            
        } 
        
        System.out.println("验证登录是否成功:"+subject.isAuthenticated());
        
        subject.logout();
        System.out.println("验证登录是否成功:"+subject.isAuthenticated());
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值