Shiro 一 用ini完成驗證

不多說什麼是shiro了,因爲我也知道皮毛。大家自己百度把。

我用的是ide2018 +maven3.2+,jdk1.8估計沒什麼影響把!

先貼出pom.xml,貼代碼的時候要貼全,部分的真心不爽看的,我看別人的深受其害。

<?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>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </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>

</project>

目錄結構貼下:

其實什麼都沒有就是個空的。

shiro.ini:

[users]
zhangsan=555
lisi=666

ShiroTest

package com.study.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

/**
 * 測試shiro認證
 */
public class ShiroTest {

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

 

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