diff --git a/spring/Apache Shiro/Apache Shiro.md b/spring/Apache Shiro/Apache Shiro.md index 62ea58b..7065b03 100644 --- a/spring/Apache Shiro/Apache Shiro.md +++ b/spring/Apache Shiro/Apache Shiro.md @@ -68,6 +68,80 @@ if ( subject.hasRole(“administrator”) ) { } else { //grey-out the button? } -``` -> 通过role来实现权限认证可能会存在问题, + +// 通过如下代码,可以实现权限分配而不是角色检测 +if ( subject.isPermitted(“user:create”) ) { + //show the ‘Create User’ button +} else { + //grey-out the button? +} +``` +权限控制甚至支持非常细粒度的权限,譬如实例级别的权限控制。 +```java +// 如下代码检测用户是否拥有删除jsmith用户的权限 +if ( subject.isPermitted(“user:delete:jsmith”) ) { + //delete the ‘jsmith’ user +} else { + //don’t delete ‘jsmith’ +} +``` +和Authentication类似,Authorization也会进入SecurityManager,并且通过一个或者多个Realm来决定是否允许访问。 +**根据需要,Realm既会响应Authentication过程,也会响应Authority过程** + +## Session Management +Apache提供了一致的会话管理,在任何类型和架构的程序中都可以使用,该Session API从小型的守护进程到大型集群web应用都可以使用。 +并且,Shiro提供的Session API是容器无关的,在任何容器环境下Session API都相同。Shiro结构也支持可插入的session存储,可以将session存储在企业缓存、关系型数据库或者nosql中。 +Shiro Seesion的另一个好处是Shiro Session可以在不同技术实现的客户端之间进行共享,譬如Swing桌面客户端可以和web客户端一起加入同一个应用会话(用户同时使用swing客户端和web客户端时很有用)。 +```java +/** +* 用户获取Session +*/ +// 如果当前用户存在会话,则获取已存在会话, +// 如果当前用户不存在会话,则创建新的会话 +Session session = subject.getSession(); +// 接受一个boolean值,该boolean值标识如果当前用户不存在会话,是否创建一个新的会话 +Session session = subject.getSession(boolean create); +``` +### Shiro Session可在任何应用中使用 +```java +Session session = subject.getSession(); +session.getAttribute(“key”, someValue); +Date start = session.getStartTimestamp(); +Date timestamp = session.getLastAccessTime(); +session.setTimeout(millis); +``` +## Shiro加密 +Shiro加密是独立于用户(Subject)的,故而Shiro加密可以独立于Subject使用。 +Shiro加密主要关注于如下两个模块: +- hash加密(又名消息摘要,message digest) +- ciphers加密 +### shiro hash +在Shiro hash中,如果想要快速计算文件的MD5值,可以通过如下方式快速计算: +```java +String hex = new Md5Hash(myFile).toHex(); +``` +在shiro hash中,如果想要对密码进行sha-512进行hash操作并且对结果进行base64编码成可打印字符串,可以进行如下操作: +```java +String encodedPassword = + new Sha512Hash(password, salt, count).toBase64(); +``` +Shiro框架在很大程度上简化了hash和编码。 +### Shiro Ciphers +Ciphers是一种算法,可以通过指定的key将加密后的数据还原到加密之前(不同于hash操作,hash操作通常是不可逆的)。通常用Ciphers来保证数据传输时的安全,防止数据在传输时被窥探。 +Shiro通过引入CipherService API来简化加密的流程,**CipherService是一个简单,无状态并且线程安全的API,可以对应用数据进行加密或者解密操作。** +```java +// Shiro CipherService对数据进行加密操作 + +AesCipherService cipherService = new AesCipherService(); +cipherService.setKeySize(256); +//create a test key: +byte[] testKey = cipherService.generateNewKey(); + +//encrypt a file’s bytes: +byte[] encrypted = + cipherService.encrypt(fileBytes, testKey); +``` +## Shiro框架的Web支持 + +