shiro 四 加密realm登錄登出

 shiro加密操作

散列算法一般用於生成數據的摘要信息,是一種不可逆的算法,一般適合存儲密碼之類的數據,常見的散列算法人MD5、SHA等。一般進行散列算法時最好提供一個鹽,比如加密密碼(admin),產生的散列值是“21232f9757a837dasddadw”,可以到一些MD5

解密網站很容易的通過散列值得到“admin”,即如果直接對密碼進行散列相對來說破解更容易,此時我們可以加一些干擾數據,如:用戶名、ID。這樣的散列的對象是“密碼+用戶名+ID”,這樣生成的散列值相對來說更難破解。

步驟:1.自定義加密之後realm:重寫3個方法:getName 、doGetAuthorizationInfo、doGetAuthenticationInfo三個方法

結構圖:

pom文件:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.study</groupId>
  <artifactId>shiro</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>shiro</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>


    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.3</version>
    </dependency>

    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.2.2</version>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
package com.study.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class PasswordRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return "PasswordRealm";
    }

    /**
     * 授權
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 認證
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 通過用戶名查找用戶信息,封裝成一個AuthenticationInfo對象返回,方便認證器進行對比
        // 獲取token中的用戶名
        String username = (String) token.getPrincipal();
        // 通過用戶名查詢數據庫,將該用戶對應的信息查詢出來:賬號,密碼
        String dbUsername = "zhangsan";
        if(!dbUsername.equals(username)){
            return null;
        }
        // 模擬數據庫保存的加密之後的密碼666 +賬號+散列次數3次
        String password = "cd757bae8bd31da92c6b14c235668091";

        // info對象表示realm登錄對比信息:參數1用戶信息,參數2,:密碼,參數3:鹽,參數4:當前realm的名字
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(dbUsername), getName());
        return simpleAuthenticationInfo;
    }
}

ini文件shiro-cryptography.ini

[main]
#定義憑證匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#散列次數
credentialsMatcher.hashIterations=3


#將憑證匹配器設置到realm
myRealm=com.study.shiro.realm.PasswordRealm
myRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealm

測試方法:

@Test
    public void testLoginByPasswordRealm() throws Exception{
        // 1.創建SecurityManager工廠對象,加載配置文件,創建
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-cryptography.ini");
        // 2.通過工廠對象,創建Securitymanage對象
        SecurityManager securityManager = factory.getInstance();
        // 3.將securitymanage綁定到當前運行環境中,讓系統隨時隨地的都可以訪問securityManager對象
        SecurityUtils.setSecurityManager(securityManager);
        // 4:創建當前登錄的主體,注意;此時主體沒有經過認證
        Subject subject = SecurityUtils.getSubject();
        // 5:綁定主體登錄的身份、憑證,即賬號密碼
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","666");
        try {
            // 6.主體登錄
            subject.login(token);
        }catch (IncorrectCredentialsException incorrectCredentialsException){
            System.out.println("密碼錯誤!");
        }catch (UnknownAccountException UnknownAccountException){
            System.out.println("用戶名錯誤!");
        }
        // 7:判斷是否登錄成功
        System.out.println("驗證是否登錄1:" + subject.isAuthenticated());
        // 8:登出
        subject.logout();
        System.out.println("驗證是否登錄2:" + subject.isAuthenticated());
    }

 

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