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());
    }
}

 

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