学Shiro完结版-2

第四章 INI配置——《跟我学Shiro》

之前章节我们已经接触过一些INI配置规则了,如果大家使用过如Spring之类的IoC/DI容器的话,Shiro提供的INI配置也是非常类似的,即可以理解为是一个IoC/DI容器,但是区别在于它从一个根对象securityManager开始。

 

4.1 根对象SecurityManager

从之前的Shiro架构图可以看出,Shiro是从根对象SecurityManager进行身份验证和授权的;也就是所有操作都是自它开始的,这个对象是线程安全且真个应用只需要一个即可,因此Shiro提供了SecurityUtils让我们绑定它为全局的,方便后续操作。

 

因为Shiro的类都是POJO的,因此都很容易放到任何IoC容器管理。但是和一般的IoC容器的区别在于,Shiro从根对象securityManager开始导航;Shiro支持的依赖注入:public空参构造器对象的创建、setter依赖注入。

 

1、纯Java代码写法(com.github.zhangkaitao.shiro.chapter4.NonConfigurationCreateTest): 

Java代码  
  1. DefaultSecurityManager securityManager = new DefaultSecurityManager();  
  2. //设置authenticator  
  3. ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();  
  4. authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());  
  5. securityManager.setAuthenticator(authenticator);  
  6.   
  7. //设置authorizer  
  8. ModularRealmAuthorizer authorizer = new ModularRealmAuthorizer();  
  9. authorizer.setPermissionResolver(new WildcardPermissionResolver());  
  10. securityManager.setAuthorizer(authorizer);  
  11.   
  12. //设置Realm  
  13. DruidDataSource ds = new DruidDataSource();  
  14. ds.setDriverClassName("com.mysql.jdbc.Driver");  
  15. ds.setUrl("jdbc:mysql://localhost:3306/shiro");  
  16. ds.setUsername("root");  
  17. ds.setPassword("");  
  18.   
  19. JdbcRealm jdbcRealm = new JdbcRealm();  
  20. jdbcRealm.setDataSource(ds);  
  21. jdbcRealm.setPermissionsLookupEnabled(true);  
  22. securityManager.setRealms(Arrays.asList((Realm) jdbcRealm));  
  23.   
  24. //将SecurityManager设置到SecurityUtils 方便全局使用  
  25. SecurityUtils.setSecurityManager(securityManager);  
  26.   
  27. Subject subject = SecurityUtils.getSubject();  
  28. UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");  
  29. subject.login(token);  
  30. Assert.assertTrue(subject.isAuthenticated());  
  31.   
  32.    

 

2.1、等价的INI配置(shiro-config.ini) 

Java代码  
  1. [main]  
  2. #authenticator  
  3. authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator  
  4. authenticationStrategy=org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy  
  5. authenticator.authenticationStrategy=$authenticationStrategy  
  6. securityManager.authenticator=$authenticator  
  7.   
  8. #authorizer  
  9. authorizer=org.apache.shiro.authz.ModularRealmAuthorizer  
  10. permissionResolver=org.apache.shiro.authz.permission.WildcardPermissionResolver  
  11. authorizer.permissionResolver=$permissionResolver  
  12. securityManager.authorizer=$authorizer  
  13.   
  14. #realm  
  15. dataSource=com.alibaba.druid.pool.DruidDataSource  
  16. dataSource.driverClassName=com.mysql.jdbc.Driver  
  17. dataSource.url=jdbc:mysql://localhost:3306/shiro  
  18. dataSource.username=root  
  19. #dataSource.password=  
  20. jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm  
  21. jdbcRealm.dataSource=$dataSource  
  22. jdbcRealm.permissionsLookupEnabled=true  
  23. securityManager.realms=$jdbcRealm   

即使没接触过IoC容器的知识,如上配置也是很容易理解的:

1、对象名=全限定类名  相对于调用public无参构造器创建对象

2、对象名.属性名=值    相当于调用setter方法设置常量值

3、对象名.属性名=$对象引用    相当于调用setter方法设置对象引用

 

2.2、Java代码(com.github.zhangkaitao.shiro.chapter4.ConfigurationCreateTest) 

Java代码  
  1. Factory<org.apache.shiro.mgt.SecurityManager> factory =  
  2.          new IniSecurityManagerFactory("classpath:shiro-config.ini");  
  3.   
  4. org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();  
  5.   
  6. //将SecurityManager设置到SecurityUtils 方便全局使用  
  7. SecurityUtils.setSecurityManager(securityManager);  
  8. Subject subject = SecurityUtils.getSubject();  
  9. UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");  
  10. subject.login(token);  
  11.   
  12. Assert.assertTrue(subject.isAuthenticated());   

如上代码是从Shiro INI配置中获取相应的securityManager实例:

1、默认情况先创建一个名字为securityManager,类型为org.apache.shiro.mgt.DefaultSecurityManager的默认的SecurityManager,如果想自定义,只需要在ini配置文件中指定“securityManager=SecurityManager实现类”即可,名字必须为securityManager,它是起始的根;

2、IniSecurityManagerFactory是创建securityManager的工厂,其需要一个ini配置文件路径,其支持“classpath:”(类路径)、“file:”(文件系统)、“url:”(网络)三种路径格式,默认是文件系统;

3、接着获取SecuriyManager实例,后续步骤和之前的一样。

 

从如上可以看出Shiro INI配置方式本身提供了一个简单的IoC/DI机制方便在配置文件配置,但是是从securityManager这个根对象开始导航。   

 

4.2 INI配置

ini配置文件类似于Java中的properties(key=value),不过提供了将key/value分类的特性,key是每个部分不重复即可,而不是整个配置文件。如下是INI配置分类: 

Java代码  
  1. [main]  
  2. #提供了对根对象securityManager及其依赖的配置  
  3. securityManager=org.apache.shiro.mgt.DefaultSecurityManager  
  4. …………  
  5. securityManager.realms=$jdbcRealm  
  6.   
  7. [users]  
  8. #提供了对用户/密码及其角色的配置,用户名=密码,角色1,角色2  
  9. username=password,role1,role2  
  10.   
  11. [roles]  
  12. #提供了角色及权限之间关系的配置,角色=权限1,权限2  
  13. role1=permission1,permission2  
  14.   
  15. [urls]  
  16. #用于web,提供了对web url拦截相关的配置,url=拦截器[参数],拦截器  
  17. /index.html = anon  
  18. /admin/** = authc, roles[admin], perms["permission1"]  

 

[main]部分

提供了对根对象securityManager及其依赖对象的配置。

创建对象 

Java代码  
  1. securityManager=org.apache.shiro.mgt.DefaultSecurityManager  

其构造器必须是public空参构造器,通过反射创建相应的实例。

 

常量值setter注入 

Java代码  
  1. dataSource.driverClassName=com.mysql.jdbc.Driver  
  2. jdbcRealm.permissionsLookupEnabled=true   

会自动调用jdbcRealm.setPermissionsLookupEnabled(true),对于这种常量值会自动类型转换。

 

对象引用setter注入 

Java代码  
  1. authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator  
  2. authenticationStrategy=org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy  
  3. authenticator.authenticationStrategy=$authenticationStrategy  
  4. securityManager.authenticator=$authenticator   

会自动通过securityManager.setAuthenticator(authenticator)注入引用依赖。

 

嵌套属性setter注入 

Java代码  
  1. securityManager.authenticator.authenticationStrategy=$authenticationStrategy   

也支持这种嵌套方式的setter注入。

 

byte数组setter注入 

Java代码  
  1. #base64 byte[]  
  2. authenticator.bytes=aGVsbG8=  
  3. #hex byte[]  
  4. authenticator.bytes=0x68656c6c6f   

默认需要使用Base64进行编码,也可以使用0x十六进制。

 

Array/Set/List setter注入 

Java代码  
  1. authenticator.array=1,2,3  
  2. authenticator.set=$jdbcRealm,$jdbcRealm   

多个之间通过“,”分割。

 

Map setter注入

Java代码  
  1. authenticator.map=$jdbcRealm:$jdbcRealm,1:1,key:abc  

即格式是:map=key:value,key:value,可以注入常量及引用值,常量的话都看作字符串(即使有泛型也不会自动造型)。        

 

实例化/注入顺序 

Java代码  
  1. realm=Realm1  
  2. realm=Realm12  
  3.   
  4. authenticator.bytes=aGVsbG8=  
  5. authenticator.bytes=0x68656c6c6f   

后边的覆盖前边的注入。

 

测试用例请参考配置文件shiro-config-main.ini。 

 

[users]部分

配置用户名/密码及其角色,格式:“用户名=密码,角色1,角色2”,角色部分可省略。如:

Java代码  
  1. [users]  
  2. zhang=123,role1,role2  
  3. wang=123   

密码一般生成其摘要/加密存储,后续章节介绍。

 

[roles]部分

配置角色及权限之间的关系,格式:“角色=权限1,权限2”;如:

Java代码  
  1. [roles]  
  2. role1=user:create,user:update  
  3. role2=*   

如果只有角色没有对应的权限,可以不配roles,具体规则请参考授权章节。

 

[urls]部分

配置url及相应的拦截器之间的关系,格式:“url=拦截器[参数],拦截器[参数],如:  

Java代码  
  1. [urls]  
  2. /admin/** = authc, roles[admin], perms["permission1"]   

具体规则参见web相关章节。 

第五章 编码/加密——《跟我学Shiro》

在涉及到密码存储问题上,应该加密/生成密码摘要存储,而不是存储明文密码。比如之前的600w csdn账号泄露对用户可能造成很大损失,因此应加密/生成不可逆的摘要方式存储。

 

5.1 编码/解码 

Shiro提供了base64和16进制字符串编码/解码的API支持,方便一些编码解码操作。Shiro内部的一些数据的存储/表示都使用了base64和16进制字符串。

Java代码  
  1. String str = "hello";  
  2. String base64Encoded = Base64.encodeToString(str.getBytes());  
  3. String str2 = Base64.decodeToString(base64Encoded);  
  4. Assert.assertEquals(str, str2);   

通过如上方式可以进行base64编码/解码操作,更多API请参考其Javadoc。

Java代码  
  1. String str = "hello";  
  2. String base64Encoded = Hex.encodeToString(str.getBytes());  
  3. String str2 = new String(Hex.decode(base64Encoded.getBytes()));  
  4. Assert.assertEquals(str, str2);   

通过如上方式可以进行16进制字符串编码/解码操作,更多API请参考其Javadoc。

 

还有一个可能经常用到的类CodecSupport,提供了toBytes(str, "utf-8") / toString(bytes, "utf-8")用于在byte数组/String之间转换。

 

5.2 散列算法

散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如MD5、SHA等。一般进行散列时最好提供一个salt(盐),比如加密密码“admin”,产生的散列值是“21232f297a57a5a743894a0e4a801fc3”,可以到一些md5解密网站很容易的通过散列值得到密码“admin”,即如果直接对密码进行散列相对来说破解更容易,此时我们可以加一些只有系统知道的干扰数据,如用户名和ID(即盐);这样散列的对象是“密码+用户名+ID”,这样生成的散列值相对来说更难破解。

Java代码  
  1. String str = "hello";  
  2. String salt = "123";  
  3. String md5 = new Md5Hash(str, salt).toString();//还可以转换为 toBase64()/toHex()   

如上代码通过盐“123”MD5散列“hello”。另外散列时还可以指定散列次数,如2次表示:md5(md5(str)):“new Md5Hash(str, salt, 2).toString()”。

  

Java代码  
  1. String str = "hello";  
  2. String salt = "123";  
  3. String sha1 = new Sha256Hash(str, salt).toString();   

使用SHA256算法生成相应的散列数据,另外还有如SHA1、SHA512算法。     

 

Shiro还提供了通用的散列支持:

Java代码  
  1. String str = "hello";  
  2. String salt = "123";  
  3. //内部使用MessageDigest  
  4. String simpleHash = new SimpleHash("SHA-1", str, salt).toString();   

通过调用SimpleHash时指定散列算法,其内部使用了Java的MessageDigest实现。

 

为了方便使用,Shiro提供了HashService,默认提供了DefaultHashService实现。

Java代码  
  1. DefaultHashService hashService = new DefaultHashService(); //默认算法SHA-512  
  2. hashService.setHashAlgorithmName("SHA-512");  
  3. hashService.setPrivateSalt(new SimpleByteSource("123")); //私盐,默认无  
  4. hashService.setGeneratePublicSalt(true);//是否生成公盐,默认false  
  5. hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//用于生成公盐。默认就这个  
  6. hashService.setHashIterations(1); //生成Hash值的迭代次数  
  7.   
  8. HashRequest request = new HashRequest.Builder()  
  9.             .setAlgorithmName("MD5").setSource(ByteSource.Util.bytes("hello"))  
  10.             .setSalt(ByteSource.Util.bytes("123")).setIterations(2).build();  
  11. String hex = hashService.computeHash(request).toHex();   

1、首先创建一个DefaultHashService,默认使用SHA-512算法;

2、可以通过hashAlgorithmName属性修改算法;

3、可以通过privateSalt设置一个私盐,其在散列时自动与用户传入的公盐混合产生一个新盐;

4、可以通过generatePublicSalt属性在用户没有传入公盐的情况下是否生成公盐;

5、可以设置randomNumberGenerator用于生成公盐;

6、可以设置hashIterations属性来修改默认加密迭代次数;

7、需要构建一个HashRequest,传入算法、数据、公盐、迭代次数。

 

SecureRandomNumberGenerator用于生成一个随机数:

Java代码  
  1. SecureRandomNumberGenerator randomNumberGenerator =  
  2.      new SecureRandomNumberGenerator();  
  3. randomNumberGenerator.setSeed("123".getBytes());  
  4. String hex = randomNumberGenerator.nextBytes().toHex();   

 

5.3 加密/解密

Shiro还提供对称式加密/解密算法的支持,如AES、Blowfish等;当前还没有提供对非对称加密/解密算法支持,未来版本可能提供。

 

AES算法实现:

Java代码  
  1. AesCipherService aesCipherService = new AesCipherService();  
  2. aesCipherService.setKeySize(128); //设置key长度  
  3. //生成key  
  4. Key key = aesCipherService.generateNewKey();  
  5. String text = "hello";  
  6. //加密  
  7. String encrptText =   
  8. aesCipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();  
  9. //解密  
  10. String text2 =  
  11.  new String(aesCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());  
  12.   
  13. Assert.assertEquals(text, text2);   

更多算法请参考示例com.github.zhangkaitao.shiro.chapter5.hash.CodecAndCryptoTest。

 

5.4 PasswordService/CredentialsMatcher

Shiro提供了PasswordService及CredentialsMatcher用于提供加密密码及验证密码服务。

Java代码  
  1. public interface PasswordService {  
  2.     //输入明文密码得到密文密码  
  3.     String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;  
  4. }  
Java代码  
  1. public interface CredentialsMatcher {  
  2.     //匹配用户输入的token的凭证(未加密)与系统提供的凭证(已加密)  
  3.     boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);  
  4. }   

Shiro默认提供了PasswordService实现DefaultPasswordService;CredentialsMatcher实现PasswordMatcher及HashedCredentialsMatcher(更强大)。

 

DefaultPasswordService配合PasswordMatcher实现简单的密码加密与验证服务

1、定义Realm(com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm)

Java代码  
  1. public class MyRealm extends AuthorizingRealm {  
  2.     private PasswordService passwordService;  
  3.     public void setPasswordService(PasswordService passwordService) {  
  4.         this.passwordService = passwordService;  
  5.     }  
  6.      //省略doGetAuthorizationInfo,具体看代码   
  7.     @Override  
  8.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  9.         return new SimpleAuthenticationInfo(  
  10.                 "wu",  
  11.                 passwordService.encryptPassword("123"),  
  12.                 getName());  
  13.     }  
  14. }   

为了方便,直接注入一个passwordService来加密密码,实际使用时需要在Service层使用passwordService加密密码并存到数据库。

 

2、ini配置(shiro-passwordservice.ini)

Java代码  
  1. [main]  
  2. passwordService=org.apache.shiro.authc.credential.DefaultPasswordService  
  3. hashService=org.apache.shiro.crypto.hash.DefaultHashService  
  4. passwordService.hashService=$hashService  
  5. hashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormat  
  6. passwordService.hashFormat=$hashFormat  
  7. hashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory  
  8. passwordService.hashFormatFactory=$hashFormatFactory  
  9.   
  10. passwordMatcher=org.apache.shiro.authc.credential.PasswordMatcher  
  11. passwordMatcher.passwordService=$passwordService  
  12.   
  13. myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm  
  14. myRealm.passwordService=$passwordService  
  15. myRealm.credentialsMatcher=$passwordMatcher  
  16. securityManager.realms=$myRealm   

2.1、passwordService使用DefaultPasswordService,如果有必要也可以自定义;

2.2、hashService定义散列密码使用的HashService,默认使用DefaultHashService(默认SHA-256算法);

2.3、hashFormat用于对散列出的值进行格式化,默认使用Shiro1CryptFormat,另外提供了Base64Format和HexFormat,对于有salt的密码请自定义实现ParsableHashFormat然后把salt格式化到散列值中;

2.4、hashFormatFactory用于根据散列值得到散列的密码和salt;因为如果使用如SHA算法,那么会生成一个salt,此salt需要保存到散列后的值中以便之后与传入的密码比较时使用;默认使用DefaultHashFormatFactory;

2.5、passwordMatcher使用PasswordMatcher,其是一个CredentialsMatcher实现;

2.6、将credentialsMatcher赋值给myRealm,myRealm间接继承了AuthenticatingRealm,其在调用getAuthenticationInfo方法获取到AuthenticationInfo信息后,会使用credentialsMatcher来验证凭据是否匹配,如果不匹配将抛出IncorrectCredentialsException异常。

 

3、测试用例请参考com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest。

 

另外可以参考配置shiro-jdbc-passwordservice.ini,提供了JdbcRealm的测试用例,测试前请先调用sql/shiro-init-data.sql初始化用户数据。

 

如上方式的缺点是:salt保存在散列值中;没有实现如密码重试次数限制。

 

HashedCredentialsMatcher实现密码验证服务

Shiro提供了CredentialsMatcher的散列实现HashedCredentialsMatcher,和之前的PasswordMatcher不同的是,它只用于密码验证,且可以提供自己的盐,而不是随机生成盐,且生成密码散列值的算法需要自己写,因为能提供自己的盐。

 

1、生成密码散列值

此处我们使用MD5算法,“密码+盐(用户名+随机数)”的方式生成散列值:

Java代码  
  1. String algorithmName = "md5";  
  2. String username = "liu";  
  3. String password = "123";  
  4. String salt1 = username;  
  5. String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();  
  6. int hashIterations = 2;  
  7.   
  8. SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations);  
  9. String encodedPassword = hash.toHex();   

如果要写用户模块,需要在新增用户/重置密码时使用如上算法保存密码,将生成的密码及salt2存入数据库(因为我们的散列算法是:md5(md5(密码+username+salt2)))。

 

2、生成Realm(com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2)

Java代码  
  1. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  2.     String username = "liu"; //用户名及salt1  
  3.     String password = "202cb962ac59075b964b07152d234b70"; //加密后的密码  
  4.     String salt2 = "202cb962ac59075b964b07152d234b70";  
  5. SimpleAuthenticationInfo ai =   
  6.         new SimpleAuthenticationInfo(username, password, getName());  
  7.     ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //盐是用户名+随机数  
  8.         return ai;  
  9. }   

此处就是把步骤1中生成的相应数据组装为SimpleAuthenticationInfo,通过SimpleAuthenticationInfo的credentialsSalt设置盐,HashedCredentialsMatcher会自动识别这个盐。

 

如果使用JdbcRealm,需要修改获取用户信息(包括盐)的sql:“select password, password_salt from users where username = ?”,而我们的盐是由username+password_salt组成,所以需要通过如下ini配置(shiro-jdbc-hashedCredentialsMatcher.ini)修改:

Java代码  
  1. jdbcRealm.saltStyle=COLUMN  
  2. jdbcRealm.authenticationQuery=select password, concat(username,password_salt) from users where username = ?  
  3. jdbcRealm.credentialsMatcher=$credentialsMatcher   

1、saltStyle表示使用密码+盐的机制,authenticationQuery第一列是密码,第二列是盐;

2、通过authenticationQuery指定密码及盐查询SQL;

 

此处还要注意Shiro默认使用了apache commons BeanUtils,默认是不进行Enum类型转型的,此时需要自己注册一个Enum转换器“BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class);”具体请参考示例“com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest”中的代码。

 

另外可以参考配置shiro-jdbc-passwordservice.ini,提供了JdbcRealm的测试用例,测试前请先调用sql/shiro-init-data.sql初始化用户数据。

 

3、ini配置(shiro-hashedCredentialsMatcher.ini)

Java代码  
  1. [main]  
  2. credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher  
  3. credentialsMatcher.hashAlgorithmName=md5  
  4. credentialsMatcher.hashIterations=2  
  5. credentialsMatcher.storedCredentialsHexEncoded=true  
  6. myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2  
  7. myRealm.credentialsMatcher=$credentialsMatcher  
  8. securityManager.realms=$myRealm   

1、通过credentialsMatcher.hashAlgorithmName=md5指定散列算法为md5,需要和生成密码时的一样;

2、credentialsMatcher.hashIterations=2,散列迭代次数,需要和生成密码时的意义;

3、credentialsMatcher.storedCredentialsHexEncoded=true表示是否存储散列后的密码为16进制,需要和生成密码时的一样,默认是base64;

 

此处最需要注意的就是HashedCredentialsMatcher的算法需要和生成密码时的算法一样。另外HashedCredentialsMatcher会自动根据AuthenticationInfo的类型是否是SaltedAuthenticationInfo来获取credentialsSalt盐。

 

4、测试用例请参考com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest。

 

密码重试次数限制

如在1个小时内密码最多重试5次,如果尝试次数超过5次就锁定1小时,1小时后可再次重试,如果还是重试失败,可以锁定如1天,以此类推,防止密码被暴力破解。我们通过继承HashedCredentialsMatcher,且使用Ehcache记录重试次数和超时时间。

 

com.github.zhangkaitao.shiro.chapter5.hash.credentials.RetryLimitHashedCredentialsMatcher:

Java代码  
  1. public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {  
  2.        String username = (String)token.getPrincipal();  
  3.         //retry count + 1  
  4.         Element element = passwordRetryCache.get(username);  
  5.         if(element == null) {  
  6.             element = new Element(username , new AtomicInteger(0));  
  7.             passwordRetryCache.put(element);  
  8.         }  
  9.         AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();  
  10.         if(retryCount.incrementAndGet() > 5) {  
  11.             //if retry count > 5 throw  
  12.             throw new ExcessiveAttemptsException();  
  13.         }  
  14.   
  15.         boolean matches = super.doCredentialsMatch(token, info);  
  16.         if(matches) {  
  17.             //clear retry count  
  18.             passwordRetryCache.remove(username);  
  19.         }  
  20.         return matches;  
  21. }   

如上代码逻辑比较简单,即如果密码输入正确清除cache中的记录;否则cache中的重试次数+1,如果超出5次那么抛出异常表示超出重试次数了。

第六章 Realm及相关对象——《跟我学Shiro》

6.1 Realm

【2.5 Realm】及【3.5 Authorizer】部分都已经详细介绍过Realm了,接下来再来看一下一般真实环境下的Realm如何实现。

  

1、定义实体及关系

 

 

 

即用户-角色之间是多对多关系,角色-权限之间是多对多关系;且用户和权限之间通过角色建立关系;在系统中验证时通过权限验证,角色只是权限集合,即所谓的显示角色;其实权限应该对应到资源(如菜单、URL、页面按钮、Java方法等)中,即应该将权限字符串存储到资源实体中,但是目前为了简单化,直接提取一个权限表,【综合示例】部分会使用完整的表结构。

 

用户实体包括:编号(id)、用户名(username)、密码(password)、盐(salt)、是否锁定(locked);是否锁定用于封禁用户使用,其实最好使用Enum字段存储,可以实现更复杂的用户状态实现。

角色实体包括:、编号(id)、角色标识符(role)、描述(description)、是否可用(available);其中角色标识符用于在程序中进行隐式角色判断的,描述用于以后再前台界面显示的、是否可用表示角色当前是否激活。

权限实体包括:编号(id)、权限标识符(permission)、描述(description)、是否可用(available);含义和角色实体类似不再阐述。

 

另外还有两个关系实体:用户-角色实体(用户编号、角色编号,且组合为复合主键);角色-权限实体(角色编号、权限编号,且组合为复合主键)。

 

sql及实体请参考源代码中的sql\shiro.sql 和 com.github.zhangkaitao.shiro.chapter6.entity对应的实体。

 

2、环境准备

为了方便数据库操作,使用了“org.springframework: spring-jdbc: 4.0.0.RELEASE”依赖,虽然是spring4版本的,但使用上和spring3无区别。其他依赖请参考源码的pom.xml。

 

3、定义ServiceDao

为了实现的简单性,只实现必须的功能,其他的可以自己实现即可。

 

PermissionService

Java代码  
  1. public interface PermissionService {  
  2.     public Permission createPermission(Permission permission);  
  3.     public void deletePermission(Long permissionId);  
  4. }  

实现基本的创建/删除权限。

 

RoleService 

Java代码  
  1. public interface RoleService {  
  2.     public Role createRole(Role role);  
  3.     public void deleteRole(Long roleId);  
  4.     //添加角色-权限之间关系  
  5.     public void correlationPermissions(Long roleId, Long... permissionIds);  
  6.     //移除角色-权限之间关系  
  7.     public void uncorrelationPermissions(Long roleId, Long... permissionIds);//  
  8. }   

相对于PermissionService多了关联/移除关联角色-权限功能。

 

UserService 

Java代码  
  1. public interface UserService {  
  2.     public User createUser(User user); //创建账户  
  3.     public void changePassword(Long userId, String newPassword);//修改密码  
  4.     public void correlationRoles(Long userId, Long... roleIds); //添加用户-角色关系  
  5.     public void uncorrelationRoles(Long userId, Long... roleIds);// 移除用户-角色关系  
  6.     public User findByUsername(String username);// 根据用户名查找用户  
  7.     public Set<String> findRoles(String username);// 根据用户名查找其角色  
  8.     public Set<String> findPermissions(String username); //根据用户名查找其权限  
  9. }   

此处使用findByUsername、findRoles及findPermissions来查找用户名对应的帐号、角色及权限信息。之后的Realm就使用这些方法来查找相关信息。

 

UserServiceImpl  

Java代码  
  1. public User createUser(User user) {  
  2.     //加密密码  
  3.     passwordHelper.encryptPassword(user);  
  4.     return userDao.createUser(user);  
  5. }  
  6. public void changePassword(Long userId, String newPassword) {  
  7.     User user =userDao.findOne(userId);  
  8.     user.setPassword(newPassword);  
  9.     passwordHelper.encryptPassword(user);  
  10.     userDao.updateUser(user);  
  11. }   

在创建账户及修改密码时直接把生成密码操作委托给PasswordHelper。

 

PasswordHelper

Java代码  
  1. public class PasswordHelper {  
  2.     private RandomNumberGenerator randomNumberGenerator =  
  3.      new SecureRandomNumberGenerator();  
  4.     private String algorithmName = "md5";  
  5.     private final int hashIterations = 2;  
  6.     public void encryptPassword(User user) {  
  7.         user.setSalt(randomNumberGenerator.nextBytes().toHex());  
  8.         String newPassword = new SimpleHash(  
  9.                 algorithmName,  
  10.                 user.getPassword(),  
  11.                 ByteSource.Util.bytes(user.getCredentialsSalt()),  
  12.                 hashIterations).toHex();  
  13.         user.setPassword(newPassword);  
  14.     }  
  15. }   

之后的CredentialsMatcher需要和此处加密的算法一样。user.getCredentialsSalt()辅助方法返回username+salt。

 

为了节省篇幅,对于DAO/Service的接口及实现,具体请参考源码com.github.zhangkaitao.shiro.chapter6。另外请参考Service层的测试用例com.github.zhangkaitao.shiro.chapter6.service.ServiceTest。

 

4、定义Realm

RetryLimitHashedCredentialsMatcher 

和第五章的一样,在此就不罗列代码了,请参考源码com.github.zhangkaitao.shiro.chapter6.credentials.RetryLimitHashedCredentialsMatcher。

  

UserRealm

另外请参考Service层的测试用例com.github.zhangkaitao.shiro.chapter6.service.ServiceTest。 

Java代码  
  1. public class UserRealm extends AuthorizingRealm {  
  2.     private UserService userService = new UserServiceImpl();  
  3.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  4.         String username = (String)principals.getPrimaryPrincipal();  
  5.         SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  
  6.         authorizationInfo.setRoles(userService.findRoles(username));  
  7.         authorizationInfo.setStringPermissions(userService.findPermissions(username));  
  8.         return authorizationInfo;  
  9.     }  
  10.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  11.         String username = (String)token.getPrincipal();  
  12.         User user = userService.findByUsername(username);  
  13.         if(user == null) {  
  14.             throw new UnknownAccountException();//没找到帐号  
  15.         }  
  16.         if(Boolean.TRUE.equals(user.getLocked())) {  
  17.             throw new LockedAccountException(); //帐号锁定  
  18.         }  
  19.         //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以在此判断或自定义实现  
  20.         SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(  
  21.                 user.getUsername(), //用户名  
  22.                 user.getPassword(), //密码  
  23.                 ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt  
  24.                 getName()  //realm name  
  25.         );  
  26.         return authenticationInfo;  
  27.     }  
  28. }   

1、UserRealm父类AuthorizingRealm将获取Subject相关信息分成两步:获取身份验证信息(doGetAuthenticationInfo)及授权信息(doGetAuthorizationInfo);

2、doGetAuthenticationInfo获取身份验证相关信息:首先根据传入的用户名获取User信息;然后如果user为空,那么抛出没找到帐号异常UnknownAccountException;如果user找到但锁定了抛出锁定异常LockedAccountException;最后生成AuthenticationInfo信息,交给间接父类AuthenticatingRealm使用CredentialsMatcher进行判断密码是否匹配,如果不匹配将抛出密码错误异常IncorrectCredentialsException;另外如果密码重试此处太多将抛出超出重试次数异常ExcessiveAttemptsException;在组装SimpleAuthenticationInfo信息时,需要传入:身份信息(用户名)、凭据(密文密码)、盐(username+salt),CredentialsMatcher使用盐加密传入的明文密码和此处的密文密码进行匹配。

3、doGetAuthorizationInfo获取授权信息:PrincipalCollection是一个身份集合,因为我们现在就一个Realm,所以直接调用getPrimaryPrincipal得到之前传入的用户名即可;然后根据用户名调用UserService接口获取角色及权限信息。

 

5、测试用例

为了节省篇幅,请参考测试用例com.github.zhangkaitao.shiro.chapter6.realm.UserRealmTest。包含了:登录成功、用户名错误、密码错误、密码超出重试次数、有/没有角色、有/没有权限的测试。

 

6.2 AuthenticationToken

 

 

 

AuthenticationToken用于收集用户提交的身份(如用户名)及凭据(如密码):

Java代码  
  1. public interface AuthenticationToken extends Serializable {  
  2.     Object getPrincipal(); //身份  
  3.     Object getCredentials(); //凭据  
  4. }   

扩展接口RememberMeAuthenticationToken:提供了“boolean isRememberMe()”现“记住我”的功能;

扩展接口是HostAuthenticationToken:提供了“String getHost()”方法用于获取用户“主机”的功能。

 

Shiro提供了一个直接拿来用的UsernamePasswordToken,用于实现用户名/密码Token组,另外其实现了RememberMeAuthenticationToken和HostAuthenticationToken,可以实现记住我及主机验证的支持。

 

6.3 AuthenticationInfo

 

 

 

AuthenticationInfo有两个作用:

1、如果Realm是AuthenticatingRealm子类,则提供给AuthenticatingRealm内部使用的CredentialsMatcher进行凭据验证;(如果没有继承它需要在自己的Realm中自己实现验证);

2、提供给SecurityManager来创建Subject(提供身份信息);

 

MergableAuthenticationInfo用于提供在多Realm时合并AuthenticationInfo的功能,主要合并Principal、如果是其他的如credentialsSalt,会用后边的信息覆盖前边的。

 

比如HashedCredentialsMatcher,在验证时会判断AuthenticationInfo是否是SaltedAuthenticationInfo子类,来获取盐信息。

 

Account相当于我们之前的User,SimpleAccount是其一个实现;在IniRealm、PropertiesRealm这种静态创建帐号信息的场景中使用,这些Realm直接继承了SimpleAccountRealm,而SimpleAccountRealm提供了相关的API来动态维护SimpleAccount;即可以通过这些API来动态增删改查SimpleAccount;动态增删改查角色/权限信息。及如果您的帐号不是特别多,可以使用这种方式,具体请参考SimpleAccountRealm Javadoc。

 

其他情况一般返回SimpleAuthenticationInfo即可。

 

6.4 PrincipalCollection

 

 

 

因为我们可以在Shiro中同时配置多个Realm,所以呢身份信息可能就有多个;因此其提供了PrincipalCollection用于聚合这些身份信息:

Java代码  
  1. public interface PrincipalCollection extends Iterable, Serializable {  
  2.     Object getPrimaryPrincipal(); //得到主要的身份  
  3.     <T> T oneByType(Class<T> type); //根据身份类型获取第一个  
  4.     <T> Collection<T> byType(Class<T> type); //根据身份类型获取一组  
  5.     List asList(); //转换为List  
  6.     Set asSet(); //转换为Set  
  7.     Collection fromRealm(String realmName); //根据Realm名字获取  
  8.     Set<String> getRealmNames(); //获取所有身份验证通过的Realm名字  
  9.     boolean isEmpty(); //判断是否为空  
  10. }   

因为PrincipalCollection聚合了多个,此处最需要注意的是getPrimaryPrincipal,如果只有一个Principal那么直接返回即可,如果有多个Principal,则返回第一个(因为内部使用Map存储,所以可以认为是返回任意一个);oneByType / byType根据凭据的类型返回相应的Principal;fromRealm根据Realm名字(每个Principal都与一个Realm关联)获取相应的Principal。

 

MutablePrincipalCollection是一个可变的PrincipalCollection接口,即提供了如下可变方法:

Java代码  
  1. public interface MutablePrincipalCollection extends PrincipalCollection {  
  2.     void add(Object principal, String realmName); //添加Realm-Principal的关联  
  3.     void addAll(Collection principals, String realmName); //添加一组Realm-Principal的关联  
  4.     void addAll(PrincipalCollection principals);//添加PrincipalCollection  
  5.     void clear();//清空  
  6. }   

目前Shiro只提供了一个实现SimplePrincipalCollection,还记得之前的AuthenticationStrategy实现嘛,用于在多Realm时判断是否满足条件的,在大多数实现中(继承了AbstractAuthenticationStrategy)afterAttempt方法会进行AuthenticationInfo(实现了MergableAuthenticationInfo)的merge,比如SimpleAuthenticationInfo会合并多个Principal为一个PrincipalCollection。

 

对于PrincipalMap是Shiro 1.2中的一个实验品,暂时无用,具体可以参考其Javadoc。接下来通过示例来看看PrincipalCollection。

 

1、准备三个Realm

MyRealm1

Java代码  
  1. public class MyRealm1 implements Realm {  
  2.     @Override  
  3.     public String getName() {  
  4.         return "a"; //realm name 为 “a”  
  5.     }  
  6.     //省略supports方法,具体请见源码  
  7.     @Override  
  8.     public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  9.         return new SimpleAuthenticationInfo(  
  10.                 "zhang", //身份 字符串类型  
  11.                 "123",   //凭据  
  12.                 getName() //Realm Name  
  13.         );  
  14.     }  
  15. }  

         

MyRealm2 

和MyRealm1完全一样,只是Realm名字为b。

  

MyRealm3

Java代码  
  1. public class MyRealm3 implements Realm {  
  2.     @Override  
  3.     public String getName() {  
  4.         return "c"; //realm name 为 “c”  
  5.     }  
  6.     //省略supports方法,具体请见源码  
  7.     @Override  
  8.     public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  9.         User user = new User("zhang", "123");  
  10.         return new SimpleAuthenticationInfo(  
  11.                 user, //身份 User类型  
  12.                 "123",   //凭据  
  13.                 getName() //Realm Name  
  14.         );  
  15.     }  
  16. }   

和MyRealm1同名,但返回的Principal是User类型。

 

2、ini配置(shiro-multirealm.ini)

Java代码  
  1. [main]  
  2. realm1=com.github.zhangkaitao.shiro.chapter6.realm.MyRealm1  
  3. realm2=com.github.zhangkaitao.shiro.chapter6.realm.MyRealm2  
  4. realm3=com.github.zhangkaitao.shiro.chapter6.realm.MyRealm3  
  5. securityManager.realms=$realm1,$realm2,$realm3   

3、测试用例(com.github.zhangkaitao.shiro.chapter6.realm.PrincialCollectionTest

因为我们的Realm中没有进行身份及凭据验证,所以相当于身份验证都是成功的,都将返回:

Java代码  
  1. Object primaryPrincipal1 = subject.getPrincipal();  
  2. PrincipalCollection princialCollection = subject.getPrincipals();  
  3. Object primaryPrincipal2 = princialCollection.getPrimaryPrincipal();   

我们可以直接调用subject.getPrincipal获取PrimaryPrincipal(即所谓的第一个);或者通过getPrincipals获取PrincipalCollection;然后通过其getPrimaryPrincipal获取PrimaryPrincipal。

 

Java代码  
  1. Set<String> realmNames = princialCollection.getRealmNames();  

获取所有身份验证成功的Realm名字。      

 

Java代码  
  1. Set<Object> principals = princialCollection.asSet(); //asList和asSet的结果一样  

将身份信息转换为Set/List,即使转换为List,也是先转换为Set再完成的。

 

Java代码  
  1. Collection<User> users = princialCollection.fromRealm("c");  

根据Realm名字获取身份,因为Realm名字可以重复,所以可能多个身份,建议Realm名字尽量不要重复。

 

6.4 AuthorizationInfo

 

 

 

AuthorizationInfo用于聚合授权信息的:

Java代码  
  1. public interface AuthorizationInfo extends Serializable {  
  2.     Collection<String> getRoles(); //获取角色字符串信息  
  3.     Collection<String> getStringPermissions(); //获取权限字符串信息  
  4.     Collection<Permission> getObjectPermissions(); //获取Permission对象信息  
  5. }   

当我们使用AuthorizingRealm时,如果身份验证成功,在进行授权时就通过doGetAuthorizationInfo方法获取角色/权限信息用于授权验证。

 

Shiro提供了一个实现SimpleAuthorizationInfo,大多数时候使用这个即可。

 

对于Account及SimpleAccount,之前的【6.3 AuthenticationInfo】已经介绍过了,用于SimpleAccountRealm子类,实现动态角色/权限维护的。

 

6.5 Subject

 

 

 

Subject是Shiro的核心对象,基本所有身份验证、授权都是通过Subject完成。

1、身份信息获取

Java代码  
  1. Object getPrincipal(); //Primary Principal  
  2. PrincipalCollection getPrincipals(); // PrincipalCollection   

 

2、身份验证

Java代码  
  1. void login(AuthenticationToken token) throws AuthenticationException;  
  2. boolean isAuthenticated();  
  3. boolean isRemembered();  

通过login登录,如果登录失败将抛出相应的AuthenticationException,如果登录成功调用isAuthenticated就会返回true,即已经通过身份验证;如果isRemembered返回true,表示是通过记住我功能登录的而不是调用login方法登录的。isAuthenticated/isRemembered是互斥的,即如果其中一个返回true,另一个返回false。

  

3、角色授权验证 

Java代码  
  1. boolean hasRole(String roleIdentifier);  
  2. boolean[] hasRoles(List<String> roleIdentifiers);  
  3. boolean hasAllRoles(Collection<String> roleIdentifiers);  
  4. void checkRole(String roleIdentifier) throws AuthorizationException;  
  5. void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException;  
  6. void checkRoles(String... roleIdentifiers) throws AuthorizationException;   

hasRole*进行角色验证,验证后返回true/false;而checkRole*验证失败时抛出AuthorizationException异常。 

 

4、权限授权验证

Java代码  
  1. boolean isPermitted(String permission);  
  2. boolean isPermitted(Permission permission);  
  3. boolean[] isPermitted(String... permissions);  
  4. boolean[] isPermitted(List<Permission> permissions);  
  5. boolean isPermittedAll(String... permissions);  
  6. boolean isPermittedAll(Collection<Permission> permissions);  
  7. void checkPermission(String permission) throws AuthorizationException;  
  8. void checkPermission(Permission permission) throws AuthorizationException;  
  9. void checkPermissions(String... permissions) throws AuthorizationException;  
  10. void checkPermissions(Collection<Permission> permissions) throws AuthorizationException;  

isPermitted*进行权限验证,验证后返回true/false;而checkPermission*验证失败时抛出AuthorizationException。

 

5、会话

Java代码  
  1. Session getSession(); //相当于getSession(true)  
  2. Session getSession(boolean create);    

类似于Web中的会话。如果登录成功就相当于建立了会话,接着可以使用getSession获取;如果create=false如果没有会话将返回null,而create=true如果没有会话会强制创建一个。

 

6、退出 

Java代码  
  1. void logout();  

 

7、RunAs  

Java代码  
  1. void runAs(PrincipalCollection principals) throws NullPointerException, IllegalStateException;  
  2. boolean isRunAs();  
  3. PrincipalCollection getPreviousPrincipals();  
  4. PrincipalCollection releaseRunAs();   

RunAs即实现“允许A假设为B身份进行访问”;通过调用subject.runAs(b)进行访问;接着调用subject.getPrincipals将获取到B的身份;此时调用isRunAs将返回true;而a的身份需要通过subject. getPreviousPrincipals获取;如果不需要RunAs了调用subject. releaseRunAs即可。

 

8、多线程

Java代码  
  1. <V> V execute(Callable<V> callable) throws ExecutionException;  
  2. void execute(Runnable runnable);  
  3. <V> Callable<V> associateWith(Callable<V> callable);  
  4. Runnable associateWith(Runnable runnable);   

实现线程之间的Subject传播,因为Subject是线程绑定的;因此在多线程执行中需要传播到相应的线程才能获取到相应的Subject。最简单的办法就是通过execute(runnable/callable实例)直接调用;或者通过associateWith(runnable/callable实例)得到一个包装后的实例;它们都是通过:1、把当前线程的Subject绑定过去;2、在线程执行结束后自动释放。

 

Subject自己不会实现相应的身份验证/授权逻辑,而是通过DelegatingSubject委托给SecurityManager实现;及可以理解为Subject是一个面门。

 

对于Subject的构建一般没必要我们去创建;一般通过SecurityUtils.getSubject()获取:

Java代码  
  1. public static Subject getSubject() {  
  2.     Subject subject = ThreadContext.getSubject();  
  3.     if (subject == null) {  
  4.         subject = (new Subject.Builder()).buildSubject();  
  5.         ThreadContext.bind(subject);  
  6.     }  
  7.     return subject;  
  8. }   

即首先查看当前线程是否绑定了Subject,如果没有通过Subject.Builder构建一个然后绑定到现场返回。

 

如果想自定义创建,可以通过:

Java代码  
  1. new Subject.Builder().principals(身份).authenticated(true/false).buildSubject()  

这种可以创建相应的Subject实例了,然后自己绑定到线程即可。在new Builder()时如果没有传入SecurityManager,自动调用SecurityUtils.getSecurityManager获取;也可以自己传入一个实例。

 

对于Subject我们一般这么使用:

1、身份验证(login)

2、授权(hasRole*/isPermitted*或checkRole*/checkPermission*)

3、将相应的数据存储到会话(Session)

4、切换身份(RunAs)/多线程身份传播

5、退出

 

 

而我们必须的功能就是1、2、5。到目前为止我们就可以使用Shiro进行应用程序的安全控制了,但是还是缺少如对Web验证、Java方法验证等的一些简化实现。    

第七章 与Web集成——《跟我学Shiro》

Shiro提供了与Web集成的支持,其通过一个ShiroFilter入口来拦截需要安全控制的URL,然后进行相应的控制,ShiroFilter类似于如Strut2/SpringMVC这种web框架的前端控制器,其是安全控制的入口点,其负责读取配置(如ini配置文件),然后判断URL是否需要登录/权限等工作。

 

7.1 准备环境

1、创建webapp应用 

此处我们使用了jetty-maven-plugin和tomcat7-maven-plugin插件;这样可以直接使用“mvn jetty:run”或“mvn tomcat7:run”直接运行webapp了。然后通过URLhttp://localhost:8080/chapter7/访问即可。

 

2、依赖 

Servlet3

Java代码  
  1. <dependency>  
  2.     <groupId>javax.servlet</groupId>  
  3.     <artifactId>javax.servlet-api</artifactId>  
  4.     <version>3.0.1</version>  
  5.     <scope>provided</scope>  
  6. </dependency>   

Servlet3的知识可以参考https://github.com/zhangkaitao/servlet3-showcase及Servlet3规范http://www.iteye.com/blogs/subjects/Servlet-3-1

 

shiro-web

Java代码  
  1. <dependency>  
  2.     <groupId>org.apache.shiro</groupId>  
  3.     <artifactId>shiro-web</artifactId>  
  4.     <version>1.2.2</version>  
  5. </dependency>   

其他依赖请参考源码的pom.xml。

 

7.2 ShiroFilter入口

1、Shiro 1.1及以前版本配置方式  

Java代码  
  1. <filter>  
  2.     <filter-name>iniShiroFilter</filter-name>  
  3.     <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>  
  4.     <init-param>  
  5.         <param-name>configPath</param-name>  
  6.         <param-value>classpath:shiro.ini</param-value>  
  7.     </init-param>  
  8. </filter>  
  9. <filter-mapping>  
  10.     <filter-name>iniShiroFilter</filter-name>  
  11.     <url-pattern>/*</url-pattern>  
  12. </filter-mapping>   

1、使用IniShiroFilter作为Shiro安全控制的入口点,通过url-pattern指定需要安全的URL;

2、通过configPath指定ini配置文件位置,默认是先从/WEB-INF/shiro.ini加载,如果没有就默认加载classpath:shiro.ini,即默认相对于web应用上下文根路径;

3、也可以通过如下方式直接内嵌ini配置文件内容到web.xml

Java代码  
  1. <init-param>  
  2.     <param-name>config</param-name>  
  3.     <param-value>  
  4.         ini配置文件贴在这  
  5.     </param-value>  
  6. </init-param>  

 

2、Shiro 1.2及以后版本的配置方式

从Shiro 1.2开始引入了Environment/WebEnvironment的概念,即由它们的实现提供相应的SecurityManager及其相应的依赖。ShiroFilter会自动找到Environment然后获取相应的依赖。

Java代码  
  1. <listener>  
  2.    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>  
  3. </listener>   

通过EnvironmentLoaderListener来创建相应的WebEnvironment,并自动绑定到ServletContext,默认使用IniWebEnvironment实现。

 

可以通过如下配置修改默认实现及其加载的配置文件位置:

Java代码  
  1. <context-param>  
  2.    <param-name>shiroEnvironmentClass</param-name>  
  3.    <param-value>org.apache.shiro.web.env.IniWebEnvironment</param-value>  
  4. </context-param>  
  5.     <context-param>  
  6.         <param-name>shiroConfigLocations</param-name>  
  7.         <param-value>classpath:shiro.ini</param-value>  
  8.     </context-param>   

shiroConfigLocations默认是“/WEB-INF/shiro.ini”,IniWebEnvironment默认是先从/WEB-INF/shiro.ini加载,如果没有就默认加载classpath:shiro.ini。

 

3、与Spring集成

Java代码  
  1. <filter>  
  2.     <filter-name>shiroFilter</filter-name>  
  3.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  4.     <init-param>  
  5.         <param-name>targetFilterLifecycle</param-name>  
  6.         <param-value>true</param-value>  
  7.     </init-param>  
  8. </filter>  
  9. <filter-mapping>  
  10.     <filter-name>shiroFilter</filter-name>  
  11.     <url-pattern>/*</url-pattern>  
  12. </filter-mapping>   

DelegatingFilterProxy作用是自动到spring容器查找名字为shiroFilter(filter-name)的bean并把所有Filter的操作委托给它。然后将ShiroFilter配置到spring容器即可:

Java代码  
  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  2. <property name="securityManager" ref="securityManager"/>  
  3. <!—忽略其他,详见与Spring集成部分 -->  
  4. </bean>   

最后不要忘了使用org.springframework.web.context.ContextLoaderListener加载这个spring配置文件即可。

因为我们现在的shiro版本是1.2的,因此之后的测试都是使用1.2的配置。

 

7.3 Web INI配置

ini配置部分和之前的相比将多出对url部分的配置。     

Java代码  
  1. [main]  
  2. #默认是/login.jsp  
  3. authc.loginUrl=/login  
  4. roles.unauthorizedUrl=/unauthorized  
  5. perms.unauthorizedUrl=/unauthorized  
  6. [users]  
  7. zhang=123,admin  
  8. wang=123  
  9. [roles]  
  10. admin=user:*,menu:*  
  11. [urls]  
  12. /login=anon  
  13. /unauthorized=anon  
  14. /static/**=anon  
  15. /authenticated=authc  
  16. /role=authc,roles[admin]  
  17. /permission=authc,perms["user:create"]   

其中最重要的就是[urls]部分的配置,其格式是: “url=拦截器[参数],拦截器[参数]”;即如果当前请求的url匹配[urls]部分的某个url模式,将会执行其配置的拦截器。比如anon拦截器表示匿名访问(即不需要登录即可访问);authc拦截器表示需要身份认证通过后才能访问;roles[admin]拦截器表示需要有admin角色授权才能访问;而perms["user:create"]拦截器表示需要有“user:create”权限才能访问。

 

url模式使用Ant风格模式

Ant路径通配符支持?、*、**,注意通配符匹配不包括目录分隔符“/”:

?:匹配一个字符,如”/admin?”将匹配/admin1,但不匹配/admin或/admin2;

*:匹配零个或多个字符串,如/admin*将匹配/admin、/admin123,但不匹配/admin/1;

**:匹配路径中的零个或多个路径,如/admin/**将匹配/admin/a或/admin/a/b。

 

url模式匹配顺序

url模式匹配顺序是按照在配置中的声明顺序匹配,即从头开始使用第一个匹配的url模式对应的拦截器链。如:

Java代码  
  1. /bb/**=filter1  
  2. /bb/aa=filter2  
  3. /**=filter3   

如果请求的url是“/bb/aa”,因为按照声明顺序进行匹配,那么将使用filter1进行拦截。

 

拦截器将在下一节详细介绍。接着我们来看看身份验证、授权及退出在web中如何实现。

 

1、身份验证(登录)

1.1、首先配置需要身份验证的url  

Java代码  
  1. /authenticated=authc  
  2. /role=authc,roles[admin]  
  3. /permission=authc,perms["user:create"]   

即访问这些地址时会首先判断用户有没有登录,如果没有登录默会跳转到登录页面,默认是/login.jsp,可以通过在[main]部分通过如下配置修改: 

Java代码  
  1. authc.loginUrl=/login  

 

1.2、登录Servlet(com.github.zhangkaitao.shiro.chapter7.web.servlet.LoginServlet 

Java代码  
  1. @WebServlet(name = "loginServlet", urlPatterns = "/login")  
  2. public class LoginServlet extends HttpServlet {  
  3.     @Override  
  4.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  5.       throws ServletException, IOException {  
  6.         req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);  
  7.     }  
  8.     @Override  
  9.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  10.       throws ServletException, IOException {  
  11.         String error = null;  
  12.         String username = req.getParameter("username");  
  13.         String password = req.getParameter("password");  
  14.         Subject subject = SecurityUtils.getSubject();  
  15.         UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
  16.         try {  
  17.             subject.login(token);  
  18.         } catch (UnknownAccountException e) {  
  19.             error = "用户名/密码错误";  
  20.         } catch (IncorrectCredentialsException e) {  
  21.             error = "用户名/密码错误";  
  22.         } catch (AuthenticationException e) {  
  23.             //其他错误,比如锁定,如果想单独处理请单独catch处理  
  24.             error = "其他错误:" + e.getMessage();  
  25.         }  
  26.         if(error != null) {//出错了,返回登录页面  
  27.             req.setAttribute("error", error);  
  28.             req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);  
  29.         } else {//登录成功  
  30.             req.getRequestDispatcher("/WEB-INF/jsp/loginSuccess.jsp").forward(req, resp);  
  31.         }  
  32.     }  
  33. }   

1、doGet请求时展示登录页面;

2、doPost时进行登录,登录时收集username/password参数,然后提交给Subject进行登录。如果有错误再返回到登录页面;否则跳转到登录成功页面(此处应该返回到访问登录页面之前的那个页面,或者没有上一个页面时访问主页)。

3、JSP页面请参考源码。

 

1.3、测试

首先输入http://localhost:8080/chapter7/login进行登录,登录成功后接着可以访问http://localhost:8080/chapter7/authenticated来显示当前登录的用户: 

Java代码  
  1. ${subject.principal}身份验证已通过。  

当前实现的一个缺点就是,永远返回到同一个成功页面(比如首页),在实际项目中比如支付时如果没有登录将跳转到登录页面,登录成功后再跳回到支付页面;对于这种功能大家可以在登录时把当前请求保存下来,然后登录成功后再重定向到该请求即可。

 

Shiro内置了登录(身份验证)的实现:基于表单的和基于Basic的验证,其通过拦截器实现。

 

2、基于Basic的拦截器身份验证

2.1、shiro-basicfilterlogin.ini配置 

Java代码  
  1. [main]  
  2. authcBasic.applicationName=please login  
  3. ………省略users  
  4. [urls]  
  5. /role=authcBasic,roles[admin]   

 

1、authcBasic是org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter类型的实例,其用于实现基于Basic的身份验证;applicationName用于弹出的登录框显示信息使用,如图:



2、[urls]部分配置了/role地址需要走authcBasic拦截器,即如果访问/role时还没有通过身份验证那么将弹出如上图的对话框进行登录,登录成功即可访问。

 

 

 

2.2、web.xml

把shiroConfigLocations改为shiro-basicfilterlogin.ini即可。

 

2.3、测试

输入http://localhost:8080/chapter7/role,会弹出之前的Basic验证对话框输入“zhang/123”即可登录成功进行访问。

 

3、基于表单的拦截器身份验证

基于表单的拦截器身份验证和【1】类似,但是更简单,因为其已经实现了大部分登录逻辑;我们只需要指定:登录地址/登录失败后错误信息存哪/成功的地址即可。

  

3.1、shiro-formfilterlogin.ini 

Java代码  
  1. [main]  
  2. authc.loginUrl=/formfilterlogin  
  3. authc.usernameParam=username  
  4. authc.passwordParam=password  
  5. authc.successUrl=/  
  6. authc.failureKeyAttribute=shiroLoginFailure  
  7.   
  8. [urls]  
  9. /role=authc,roles[admin]   

1、authc是org.apache.shiro.web.filter.authc.FormAuthenticationFilter类型的实例,其用于实现基于表单的身份验证;通过loginUrl指定当身份验证时的登录表单;usernameParam指定登录表单提交的用户名参数名;passwordParam指定登录表单提交的密码参数名;successUrl指定登录成功后重定向的默认地址(默认是“/”)(如果有上一个地址会自动重定向带该地址);failureKeyAttribute指定登录失败时的request属性key(默认shiroLoginFailure);这样可以在登录表单得到该错误key显示相应的错误消息;

 

3.2、web.xml

把shiroConfigLocations改为shiro- formfilterlogin.ini即可。

 

3.3、登录Servlet 

Java代码  
  1. @WebServlet(name = "formFilterLoginServlet", urlPatterns = "/formfilterlogin")  
  2. public class FormFilterLoginServlet extends HttpServlet {  
  3.     @Override  
  4.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  5.       throws ServletException, IOException {  
  6.         doPost(req, resp);  
  7.     }  
  8.     @Override  
  9.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  10.      throws ServletException, IOException {  
  11.         String errorClassName = (String)req.getAttribute("shiroLoginFailure");  
  12.         if(UnknownAccountException.class.getName().equals(errorClassName)) {  
  13.             req.setAttribute("error", "用户名/密码错误");  
  14.         } else if(IncorrectCredentialsException.class.getName().equals(errorClassName)) {  
  15.             req.setAttribute("error", "用户名/密码错误");  
  16.         } else if(errorClassName != null) {  
  17.             req.setAttribute("error", "未知错误:" + errorClassName);  
  18.         }  
  19.         req.getRequestDispatcher("/WEB-INF/jsp/formfilterlogin.jsp").forward(req, resp);  
  20.     }  
  21. }  

在登录Servlet中通过shiroLoginFailure得到authc登录失败时的异常类型名,然后根据此异常名来决定显示什么错误消息。

 

4、测试

输入http://localhost:8080/chapter7/role,会跳转到“/formfilterlogin”登录表单,提交表单如果authc拦截器登录成功后,会直接重定向会之前的地址“/role”;假设我们直接访问“/formfilterlogin”的话登录成功将直接到默认的successUrl。

 

4、授权(角色/权限验证)

4.1、shiro.ini   

Java代码  
  1. [main]  
  2. roles.unauthorizedUrl=/unauthorized  
  3. perms.unauthorizedUrl=/unauthorized  
  4.  [urls]  
  5. /role=authc,roles[admin]  
  6. /permission=authc,perms["user:create"]   

通过unauthorizedUrl属性指定如果授权失败时重定向到的地址。roles是org.apache.shiro.web.filter.authz.RolesAuthorizationFilter类型的实例,通过参数指定访问时需要的角色,如“[admin]”,如果有多个使用“,”分割,且验证时是hasAllRole验证,即且的关系。Perms是org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter类型的实例,和roles类似,只是验证权限字符串。

 

4.2、web.xml

把shiroConfigLocations改为shiro.ini即可。

 

4.3、RoleServlet/PermissionServlet  

Java代码  
  1. @WebServlet(name = "permissionServlet", urlPatterns = "/permission")  
  2. public class PermissionServlet extends HttpServlet {  
  3.     @Override  
  4.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  5.       throws ServletException, IOException {  
  6.         Subject subject = SecurityUtils.getSubject();  
  7.         subject.checkPermission("user:create");  
  8.         req.getRequestDispatcher("/WEB-INF/jsp/hasPermission.jsp").forward(req, resp);  
  9.     }  
  10. }  
Java代码  
  1. @WebServlet(name = "roleServlet", urlPatterns = "/role")  
  2. public class RoleServlet extends HttpServlet {  
  3.     @Override  
  4.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  5.       throws ServletException, IOException {  
  6.         Subject subject = SecurityUtils.getSubject();  
  7.         subject.checkRole("admin");  
  8.         req.getRequestDispatcher("/WEB-INF/jsp/hasRole.jsp").forward(req, resp);  
  9.     }  
  10. }   

 

4.4、测试

首先访问http://localhost:8080/chapter7/login,使用帐号“zhang/123”进行登录,再访问/role或/permission时会跳转到成功页面(因为其授权成功了);如果使用帐号“wang/123”登录成功后访问这两个地址会跳转到“/unauthorized”即没有授权页面。

 

5、退出

5.1、shiro.ini 

Java代码  
  1. [urls]  
  2. /logout=anon   

指定/logout使用anon拦截器即可,即不需要登录即可访问。

 

5.2、LogoutServlet

Java代码  
  1. @WebServlet(name = "logoutServlet", urlPatterns = "/logout")  
  2. public class LogoutServlet extends HttpServlet {  
  3.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  4.       throws ServletException, IOException {  
  5.         SecurityUtils.getSubject().logout();  
  6.         req.getRequestDispatcher("/WEB-INF/jsp/logoutSuccess.jsp").forward(req, resp);  
  7.     }  
  8. }   

直接调用Subject.logout即可,退出成功后转发/重定向到相应页面即可。

 

5.3、测试

首先访问http://localhost:8080/chapter7/login,使用帐号“zhang/123”进行登录,登录成功后访问/logout即可退出。

 

Shiro也提供了logout拦截器用于退出,其是org.apache.shiro.web.filter.authc.LogoutFilter类型的实例,我们可以在shiro.ini配置文件中通过如下配置完成退出:

Java代码  
  1. [main]  
  2. logout.redirectUrl=/login  
  3.   
  4. [urls]  
  5. /logout2=logout   

通过logout.redirectUrl指定退出后重定向的地址;通过/logout2=logout指定退出url是/logout2。这样当我们登录成功后然后访问/logout2即可退出。

 

posted @ 2022-02-16 15:27  hanease  阅读(40)  评论(0编辑  收藏  举报