Shiro可以对以下4个方面进行安全控制
- Authentication 认证
- Authorization 授权
- Cryptography 加密,保护隐私数据
- Session Management 回话管理
Shiro的认证:
捕获用户登录异常信息,如用户名或密码错误,抛出对应的异常
try {
currentUser.login(token);
} catch (IncorrectCredentialsException ice) { …
} catch (LockedAccountException lae) { …
}
…
catch (AuthenticationException ae) {…
}
Shiro的授权
用户权限判断:
if ( subject.hasRole(“administrator”) ) {
//show the ‘Create User’ button
} else {
//grey-out the button?
}
可以重写权限检查,代替原有的权限检查
if ( subject.isPermitted(“user:create”) ) {
// show the ‘Create User’ button
} else {
// grey-out the button?
}
Shiro的回话管理机制,可以代替EJB和Servlet
获取会话:
Session session = subject.getSession();// 获取一个会话,如果当前没有会话,则创建一个新的回话返回
Session session = subject.getSession(boolean create); //获取一个会话,如果会话不存在,通过boolean值判断是否创建一个新的会话
Shiro的回话能使用在任何场景,不单单是web应用中,shiro的回话,保留HttpSession的特性,基本上可以将其看做HTTPSession
Shiro的加密
目的:为了简化JDK的加密支持
Shiro支持两种加密方式:cryptographic hashes 和 cryptographic ciphers
cryptographic hashes:可已经使用例如MD5加密,将密码通过MessageDigest加密成hash数组,hash数组可以进行位运算
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.digest(bytes);
byte[] hashed = md.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
获得16为的MD5加密后的密码
String hex = new Md5Hash(myFile).toHex();
可以很容易的进行SHA512加密或者是Base64加密
String encodedPassword = new Sha512Hash(password, salt, count).toBase64();
cryptographic ciphers:使用密钥可逆地转换数据的加密算法,可以进行加密和解密
可以使用ciphers进行:公钥私钥加密,使用Block Cipher进行流操作,创建AES 256位的密码
使用shiro的ciphers进行加密解密相对于JDK的容易很多
通过CipherService进行加密和解密:
AesCipherService cipherService = new AesCipherService(); // 创建CipherService实例
cipherService.setKeySize(256); // 设置进行256位进行加密
//获取一个密码
byte[] testKey = cipherService.generateNewKey();
//获取加密文件的字节数组
byte[] encrypted = cipherService.encrypt(fileBytes, testKey);
Shiro的Web Support
只需要在web.xml文件中加入shiro过滤器
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>
org.apache.shiro.web.servlet.IniShiroFilter
</filter-class>
<!-- no init-param means load the INI config
from classpath:shiro.ini -->
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Shiro的3个核心概念:
Subject:
用户的登录,登出
//1. 提交用户名和密码
AuthenticationToken token = new UsernamePasswordToken(username, password);
//2.获取当前用户
Subject currentUser = SecurityUtils.getSubject();
//3.登录
currentUser.login(token);
当login方法被调用时,SecurityManager将接收到的authenticationtoken分派到Realms,Realms进行检查,可以进行try…catch 操作,判断用户名和密码是否正确
SecurityManager:用户的操作权限
//加载ini配置文件,配置SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//创建SecurityManager实例,使用的是工厂模式
SecurityManager securityManager = factory.getInstance();
//设置SecurityManager为单例,一般不需要设置,根据需求进行设置
SecurityUtils.setSecurityManager(securityManager);
Realms: shiro进行权限验证,用来连接shiro和应用程序之间的数据传递(如:链接数据库),至少一个,可以设置多个