首先创建一个maven项目,导入以下jar包:
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
配置文件shiro.ini
[users]
gates=123456
root=123456
主要代码
package com.shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
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 HelloWorld {
public static void main(String[] args) {
//读取配置文件,初始化SecurityManager工厂
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");
//获取SecurityManager实例
SecurityManager securityManager=factory.getInstance();
//把SecurityManager实例绑定到SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
//得到当前执行的用户
Subject currentUser=SecurityUtils.getSubject();
//创建token令牌,用户名/密码
UsernamePasswordToken token=new UsernamePasswordToken("gates","12356");
try {
//身份认证,即登录
currentUser.login(token);
System.out.println("success");
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("failed");
}
currentUser.logout();
}
}
Subject认证主体主要包含两部分:
1、principals:即身份,可以是用户名、手机号码、邮件等等,用来标识一个登录主体身份。
2、credentials:即凭证,常见的有密码、数字证书等等。