初學shiro,對shiro的一些認知,測試完整代碼(基于junit)如下:
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 shiroTest {
//建立relam(simplerelam)
SimpleAccountRealm sar=new SimpleAccountRealm();
@Before
public void addUser(){
//模拟資料庫的資料
sar.addAccount("Salong","123456");
}
@Test
public void test(){
//建構secuityManage環境,建立對象
DefaultSecurityManager dsm= new DefaultSecurityManager();
//将relam加入到securityManage環境中
dsm.setRealm(sar);
//主體送出認證請求
SecurityUtils.setSecurityManager(dsm);
Subject sub=SecurityUtils.getSubject();
//擷取賬号和密碼(模拟用戶端提供的資料)
UsernamePasswordToken token=new UsernamePasswordToken("Salong","123456");
//認證
sub.login(token);
System.out.println("是否認證:"+sub.isAuthenticated());//true
//退出認證
sub.logout();
System.out.println("是否認證:"+sub.isAuthenticated());//false
}
}
最後測試成功,達到預期的效果