初学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
}
}
最后测试成功,达到预期的效果