Springboot整合Shiro之加鹽MD5加密的方法
更新時間:2018年12月03日 11:00:34 作者:夢想周游全國的孩子
這篇文章主要介紹了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;
}
總結
以上所述是小編給大家介紹的Springboot整合Shiro之加鹽MD5加密的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
您可能感興趣的文章:
相關文章
用Java連接sqlserver數據庫時候幾個jar包的區(qū)別分析
這篇文章主要介紹了用Java連接sqlserver數據庫時候幾個jar包的區(qū)別分析,需要的朋友可以參考下2014-10-10

