Springboot整合Shiro之加鹽MD5加密的方法

這篇文章主要介紹了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加密的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章