2019獨角獸企業重金招聘Python工程師標準>>>
一、登錄驗證
1、首先在shiro.ini里準備一些用戶身份/憑據,后面這里會使用數據庫代替,如:
[users]
[main]
#realm
jdbcRealm=com.learnging.system.shiro.ShiroRealm
securityManager.realm=$jdbcRealm
authc = org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authc.loginUrl = /[urls]
/index = authc
/a/logout = logout
2登錄測試
準備知識: (1)當運行Web應用程序時,Shiro將創建一些有用的內置過濾器實例,并且自動的在[main]部分使用。如.ini文件配置,要使用authc,先定義其使用的類,這個類必須實現AuthenticatingFilter。這里也可以使用shiro已經實現好的一些AuthenticationFilter,如PassThruAuthenticationFilter,FormAuthenticationFilter。
(2)使用shiro的.ini文件路徑前一定要加CLASSPATH、URL、FILE前綴,如classpath:shiro.ini;只需把shiro.ini放在resources文件夾下,它就能自動找到shiro文件。
測試用例如下:
package learning_system;
import junit.framework.Assert;
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.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;public class LoginLogoutTest
{@Testpublic void testHelloworld(){//1、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManagerFactory<org.apache.shiro.mgt.SecurityManager> factory =new IniSecurityManagerFactory("classpath:shiro.ini");//2、得到SecurityManager實例 并綁定給SecurityUtilsorg.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);//3、得到Subject及創建用戶名/密碼身份驗證Token(即用戶身份/憑證)Subject subject = SecurityUtils.getSubject();UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");try{//4、登錄,即身份驗證subject.login(token);}catch (AuthenticationException e){//5、身份驗證失敗}Assert.assertEquals(true, subject.isAuthenticated()); //斷言用戶已經登錄//6、退出subject.logout();}
}
web項目可以省略以上的如下代碼,web容器會幫你做:
Factory<org.apache.shiro.mgt.SecurityManager> factory =new IniSecurityManagerFactory("classpath:shiro.ini");org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);