shiro配置加密

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

[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());
    }

猜你喜欢

转载自blog.csdn.net/qq_25635139/article/details/84760219