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

本文介绍了如何在Springboot项目中整合Shiro进行加盐MD5加密。通过自定义realm,重写相关方法,将用户信息与加密后的密码结合使用SimpleAuthenticationInfo,并在Shiro配置中指定加密方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值