【二】shiro入門 之 身份驗證

大致步驟以下:web

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

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

三、經過SecurityUtils獲得Subject,其會自動綁定到當前線程;若是在web環境在請求結束時須要解除綁定;而後獲取身份驗證的Token,如用戶名/密碼;spa

四、調用subject.login 方法進行登陸,其會自動委託給SecurityManager.login方法進行登陸;線程

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

六、最後能夠調用subject.logout退出,其會自動委託給SecurityManager.logout方法退出。blog

示例繼承

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

<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)ci

[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() {
        // 一、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManager
        Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //二、獲得SecurityManager實例並綁定給SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //三、獲得Subject及建立用戶名/密碼身份驗證Token(即用戶身份/憑證)
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhang", "1223");
        
        try {
        //四、登陸,即身份驗證
        subject.login(token);
        } catch (AuthenticationException e) {
          //五、身份驗證失敗
            System.out.println("身份驗證失敗");
        }
        
        //斷言用戶已經登陸
        Assert.assertEquals(true, subject.isAuthenticated());
        
        subject.logout();
    }
}
相關文章
相關標籤/搜索