? 搭建springboot項目,引入以下依賴:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--單元測試--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--shiro--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.2</version></dependency></dependencies>
一、身份驗證:
1、登錄/退出:
(1)數據mock:新建shiro-user.ini文件
[users]
zs=123
ls=123
admin=123
(2)單元測試:
import com.demo.shiro.ShiroApplication;
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.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;/*** 身份驗證*/
@SpringBootTest(classes = {ShiroApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class ShiroAuthenticationTest {/*** 1、登陸/退出,以admin/123用戶為例*/@Testpublic void testLoginInAndPut(){//1、創建SecurityManagerFactory,用戶名/密碼硬編碼在ini文件,實際應存儲在數據庫并將密碼加密IniSecurityManagerFactory factory=new IniSecurityManagerFactory("classpath:shiro-user.ini");//2、創建安全管理器SecurityManager,并綁定給SecurityUtilSecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);//3、通過SecurityUtil獲取登入用戶主體subject,并創建tokenSubject subject = SecurityUtils.getSubject();UsernamePasswordToken token=new UsernamePasswordToken("admin", "123");//用戶認證(shrio的核心功能之一)try {//異常//4、登錄,即身份驗證subject.login(token);System.out.println("認證成功");} catch (AuthenticationException e) {//5、認證失敗//org.apache.shiro.authc.UnknownAccountException:賬號錯誤異常//org.apache.shiro.authc.IncorrectCredentialsException:密碼錯誤異常//org.apache.shiro.authz.UnauthorizedException: 授權錯誤異常System.out.println("認證失敗");e.printStackTrace();}//6、安全退出subject.logout();}
}
執行,控制臺輸出:認證成功;
將密碼改為123456,拋出密碼錯誤異常
如上代碼可總結出身份驗證的步驟:
1)收集用戶身份 / 憑證,即如用戶名 / 密碼;
2)調用 Subject.login 進行登錄,如果失敗將得到相應的 AuthenticationException 異常,根據異常提示用戶錯誤信息;否則登錄成功;
3)最后調用 Subject.logout 進行退出操作。?
二、角色驗證: