shairo快速上手

1、Maven依赖

 <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.1</version>
        </dependency>
        <dependency>
            <groupId> org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId> log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId> org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12 </version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

2、在resource目录下新建shiro.ini文件存放账号信息

#配置用户
[users]
#用户名=密码
xiangwen=123456
xiangwu= 123

3、新建ShiroTest类

package com.xiangwen.test;

import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
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;


public class ShiroTest {
public static void main(String[] args) {
//1、读取配置文件,创建安全管理器:SecurityManager
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager=factory.createInstance();
//2、将工厂对象和当前线程绑定
SecurityUtils.setSecurityManager(securityManager);
//3、从当前线程获取主体对象
Subject subject=SecurityUtils.getSubject();

//5、判断是否认证
boolean authentic=subject.isAuthenticated();
System.out.println("认证前:"+authentic);
//6、开始认证
if(!authentic){
//4、创建token令牌:封装身份(账号)和凭证(密码)
AuthenticationToken token=new UsernamePasswordToken("xiangwen","123456");

try {
subject.login(token);
authentic=subject.isAuthenticated();
}catch (UnknownAccountException e){
System.out.println("无效账号");
}catch (IncorrectCredentialsException e){
System.out.println("无效密码");
}
System.out.println("认证后:"+authentic);

}
//7、获取认证信息
Object person=subject.getPrincipal();
System.out.println("person:"+person);
//8、退出登录
subject.logout();
authentic=subject.isAuthenticated();
System.out.println("退出认证后:"+authentic);
}
}

  

上一篇:08 Shrio 授权的三种方式


下一篇:thinkphp6自动写入时间戳字段相关