【二】shiro入門 之 身份驗證


大體步驟如下:

1.首先通過new IniSecurityManagerFactory 並指定一個ini 配置文件來創建一個SecurityManager工廠;

2.接着獲取SecurityManager並綁定到SecurityUtils,這是一個全局設置,設置一次即可;

3、通過SecurityUtils得到Subject,其會自動綁定到當前線程;如果在web環境在請求結束時需要解除綁定;然后獲取身份驗證的Token,如用戶名/密碼;

4、調用subject.login 方法進行登錄,其會自動委托給SecurityManager.login方法進行登錄;

5、如果身份驗證失敗請捕獲AuthenticationException 或其子類,常見的如:
DisabledAccountException(禁用的帳號)、LockedAccountException(鎖定的帳號)、
UnknownAccountException(錯誤的帳號)、ExcessiveAttemptsException(登錄失敗次數過
多)、IncorrectCredentialsException (錯誤的憑證)、ExpiredCredentialsException(過期的
憑證)等,具體請查看其繼承關系;對於頁面的錯誤消息展示,最好使用如“用戶名/密碼
錯誤”而不是“用戶名錯誤”/“密碼錯誤”,防止一些惡意用戶非法掃描帳號庫;

6、最后可以調用subject.logout退出,其會自動委托給SecurityManager.logout方法退出。

示例

1.添加junit、common-logging及shiro-core 依賴

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
        </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>
    </dependencies>

2.准備一些用戶身份/憑據(shiro.ini)

[users]
zhang=123
wang=123

3.測試用例

package me.shijunjie.testshiro;

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.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

import junit.framework.Assert;

public class TestShiro {
    @Test
    public void testHelloworld() {
        // 1、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManager
        Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //2、得到SecurityManager實例並綁定給SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //3、得到Subject及創建用戶名/密碼身份驗證Token(即用戶身份/憑證)
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhang", "1223");
        
        try {
        //4、登錄,即身份驗證
        subject.login(token);
        } catch (AuthenticationException e) {
          //5、身份驗證失敗
            System.out.println("身份驗證失敗");
        }
        
        //斷言用戶已經登錄
        Assert.assertEquals(true, subject.isAuthenticated());
        
        subject.logout();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM