Springboot整合Shiro----加盐MD5加密

1.自定义realm,在Shiro的配置类中加入以下bean

/**
     * 身份认证 realm
     */
    @Bean
    public MyShiroRealm myShiroRealm(){
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        System.out.println("myShiroRealm 注入成功");
        return myShiroRealm;
    }

2.重写方法

// 身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();

        System.out.println("MyShiroRealm.....doGetAuthenticationInfo");
        UserInfo user=null;
        try {
            user = iUserInfoService.findByUsername(username);
        }catch (Exception e){
            e.printStackTrace();
        }

        if (user==null){
            return null;
        }

        // 进行验证,将正确数据讲给shiro处理
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),  // 加盐后的密码
                getName() // 指定当前 Realm 的类名
        );




        // 返回给安全管理器,由 securityManager 比对密码的正确性
        return authenticationInfo;

    }

需要注意的是SimpleAuthenticationInfo 类,我们需要把数据交给他,格式为(用户,用户密码,盐,当前Realm的类名)

        // 进行验证,将正确数据讲给shiro处理
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),  // 加盐后的密码
                getName() // 指定当前 Realm 的类名
        );

3.你还需要告诉shiro你是经过加密的,在Config内新建如下bean

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 使用md5 算法进行加密
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        // 设置散列次数: 意为加密几次
        hashedCredentialsMatcher.setHashIterations(2);

        return hashedCredentialsMatcher;
    }

并注册:

 @Bean
    public MyShiroRealm myShiroRealm(){
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        // 配置 加密 (在加密后,不配置的话会导致登陆密码失败)
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());  //+++++++++++
        System.out.println("myShiroRealm 注入成功");
        return myShiroRealm;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章