shiro身份驗證測試

1、登陸驗證web

一、首先在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登陸測試apache

準備知識: (1)當運行Web應用程序時,Shiro將建立一些有用的內置過濾器實例,而且自動的在[main]部分使用。如.ini文件配置,要使用authc,先定義其使用的類,這個類必須實現AuthenticatingFilter。這裏也能夠使用shiro已經實現好的一些AuthenticationFilter,如PassThruAuthenticationFilter,FormAuthenticationFilter。測試

(2)使用shiro的.ini文件路徑前必定要加CLASSPATH、URL、FILE前綴,如classpath:shiro.ini;只需把shiro.ini放在resources文件夾下,它就能自動找到shiro文件。url

測試用例以下:spa

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
{
    @Test
    public void testHelloworld()
    {
        //一、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManager
        Factory<org.apache.shiro.mgt.SecurityManager> factory =
            new IniSecurityManagerFactory("classpath:shiro.ini");

        //二、獲得SecurityManager實例 並綁定給SecurityUtils
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //三、獲得Subject及建立用戶名/密碼身份驗證Token(即用戶身份/憑證)
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");

        try
        {
            //四、登陸,即身份驗證
            subject.login(token);
        }
        catch (AuthenticationException e)
        {
            //五、身份驗證失敗
        }

        Assert.assertEquals(true, subject.isAuthenticated()); //斷言用戶已經登陸

        //六、退出
        subject.logout();
    }
}

web項目能夠省略以上的以下代碼,web容器會幫你作:code

Factory<org.apache.shiro.mgt.SecurityManager> factory =
         new IniSecurityManagerFactory("classpath:shiro.ini");
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
相關文章
相關標籤/搜索