Springboot整合Shiro之加盐MD5加密的方法
1.自定义realm,在Shiro的配置类中加入以下bean
/** *身份认证realm */ @Bean publicMyShiroRealmmyShiroRealm(){ MyShiroRealmmyShiroRealm=newMyShiroRealm(); System.out.println("myShiroRealm注入成功"); returnmyShiroRealm; }
2.重写方法
//身份认证 @Override protectedAuthenticationInfodoGetAuthenticationInfo(AuthenticationTokenauthenticationToken)throwsAuthenticationException{ Stringusername=(String)authenticationToken.getPrincipal(); System.out.println("MyShiroRealm.....doGetAuthenticationInfo"); UserInfouser=null; try{ user=iUserInfoService.findByUsername(username); }catch(Exceptione){ e.printStackTrace(); } if(user==null){ returnnull; } //进行验证,将正确数据讲给shiro处理 SimpleAuthenticationInfoauthenticationInfo=newSimpleAuthenticationInfo( user, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()),//加盐后的密码 getName()//指定当前Realm的类名 ); //返回给安全管理器,由securityManager比对密码的正确性 returnauthenticationInfo; }
需要注意的是SimpleAuthenticationInfo类,我们需要把数据交给他,格式为(用户,用户密码,盐,当前Realm的类名)
//进行验证,将正确数据讲给shiro处理 SimpleAuthenticationInfoauthenticationInfo=newSimpleAuthenticationInfo( user, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()),//加盐后的密码 getName()//指定当前Realm的类名 );
3.你还需要告诉shiro你是经过加密的,在Config内新建如下bean
@Bean publicHashedCredentialsMatcherhashedCredentialsMatcher(){ HashedCredentialsMatcherhashedCredentialsMatcher=newHashedCredentialsMatcher(); //使用md5算法进行加密 hashedCredentialsMatcher.setHashAlgorithmName("md5"); //设置散列次数:意为加密几次 hashedCredentialsMatcher.setHashIterations(2); returnhashedCredentialsMatcher; }
并注册:
@Bean publicMyShiroRealmmyShiroRealm(){ MyShiroRealmmyShiroRealm=newMyShiroRealm(); //配置加密(在加密后,不配置的话会导致登陆密码失败) myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());//+++++++++++ System.out.println("myShiroRealm注入成功"); returnmyShiroRealm; }
总结
以上所述是小编给大家介绍的Springboot整合Shiro之加盐MD5加密的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!