Shiro targets what the Shiro development team calls “the four cornerstones of application security” - Authentication(身份认证), Authorization(权限控制), Session Management(Session管理), and Cryptography(加密):
Authentication: Sometimes referred to as ‘login’, this is the act of proving a user is who they say they are.
Authorization: The process of access control, i.e. determining ‘who’ has access to ‘what’.
Session Management: Managing user-specific sessions, even in non-web or EJB applications.
Cryptography: Keeping data secure using cryptographic algorithms while still being easy to use.
前面四个是核心的。
还具有Web支持,缓存,并发,伪装,”记住我”等
1、创建一个Maven工程,并配置依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
2、配置配置文件shiro.ini(放在resource文件下)
[users]
admin=123456
tony=12345
3、创建HelloWord类
package com.lpc.helloShiro1;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWord {
private static Logger logger = LoggerFactory.getLogger(HelloWord.class);
public static void main(String[] args) {
// IniSecurityManagerFactory方法在1.4.0中被注解标志为不建议使用
// 读取配置文件,初始化SecurityManager工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 获取securityManager 实例
SecurityManager securityManager = factory.getInstance();
// 把securityManager实例绑定到SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
// 得到当前执行的用户
Subject subject = SecurityUtils.getSubject();// 认证实体,当前进来的用户
// 创建token令牌,用户名/密码
UsernamePasswordToken token = new UsernamePasswordToken("tony", "12345");
// 身份认证
try {
subject.login(token);
logger.info("登录成功!");
} catch (AuthenticationException e) {
// login的接口函数 void login(AuthenticationToken var1) throws
// AuthenticationException;所以直接抓AuthenticationException异常即可
// 身份认证失败即抛出此异常
logger.info("登录失败!");
e.printStackTrace();
}
// 登出
subject.logout();
}
}