创建工程:
test测试类:
package com.sxt.test;
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;
import org.junit.Test;
public class test {
public static void main(String[] args) {
//获取SecurityManager工厂对象
Factory<SecurityManager> factory=
new IniSecurityManagerFactory("classpath:shiro.ini");
//通过Factory对象SecurityManager对象
SecurityManager securityManager=factory.getInstance();
//将SecurityManager对象添加到运行环境中
SecurityUtils.setSecurityManager(securityManager);
// 4.获取Subject对象
Subject subject=SecurityUtils.getSubject();
AuthenticationToken token=new UsernamePasswordToken("root","123456");
//登录操作
try{
subject.login(token);
System.out.println("认证成功");
}catch(UnknownAccountException e){
System.out.println("账号出错");
}catch(IncorrectCredentialsException e){
System.out.println("密码错误");
}
}
}
shiro.ini:
[users]
root=123456
#账号,密码
pom.xml依赖!
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
测试: