對shiro的初步理解

Apache Shiro是一個強大且易用的Java安全框架,執行身份驗證、授權、密碼和會話管理。

其中 SecurityManager是核心,相當於Spring MVC的前端控制器,起管家調度作用。

        Subject可以理解爲賬戶。來驗證其是否合法或者權限。

        Realms可以理解爲數據源,即程序從Realm中拿數據來確認該用戶時候是合法,權限等。Realm可以自己實現,繼承Realm即可。下面這個例子默認Realm的來源爲ini配置文件,即zhang=123  wang =123.符合這兩個即ok.

先不多說,看代碼:

@Test//導入Junit包
    public void testWorld() {
        //1、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManager
        //shiro配置文件放在src/test/resource目錄下,配置文件內容:
        [users]
         zhang=123
         wang=123
        Factory<org.apache.shiro.mgt.SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro.ini");

        //2、得到SecurityManager實例 並綁定給SecurityUtils
        org.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、身份驗證失敗
        	try {
				throw new Exception("失敗了");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
        }
        Assert.assertEquals(true, subject.isAuthenticated()); //斷言用戶已經登錄

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

jar包的引入:

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
         <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency> 
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.2</version>
        </dependency>
 <dependency>
//這個包容易忘記
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.7.2</version>
   </dependency> 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章