1.自定義realm,在Shiro的配置類中加入以下bean
創(chuàng)新互聯(lián)主營黔江網站建設的網絡公司,主營網站建設方案,成都APP應用開發(fā),黔江h(huán)5成都小程序開發(fā)搭建,黔江網站營銷推廣歡迎黔江等地區(qū)企業(yè)咨詢
/** * 身份認證 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; }
總結
以上所述是小編給大家介紹的Springboot整合Shiro之加鹽MD5加密的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對創(chuàng)新互聯(lián)網站的支持!