Shiro認證實戰
阿新 • • 發佈:2018-11-07
一 Shiro認證流程圖
二 實戰
1 新建pom
<dependencies> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> </dependency> </dependencies>
2 測試認證
package com.liuyanzhao.test; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.SimpleAccountRealm; import org.apache.shiro.subject.Subject; import org.junit.Before; import org.junit.Test; public class AuthenticationTest { SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm(); @Before public void addUser() { simpleAccountRealm.addAccount("Tom","1234567"); } @Test public void testAuthentication() { //1、構建SecurityManager環境 DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(); defaultSecurityManager.setRealm(simpleAccountRealm); //2、主體提交認證請求 SecurityUtils.setSecurityManager(defaultSecurityManager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("Tom","1234567"); subject.login(token); System.out.println("isAuthenticated:"+subject.isAuthenticated()); subject.logout(); System.out.println("isAuthenticated:"+subject.isAuthenticated()); } }
三 測試結果
isAuthenticated:true
isAuthenticated:false