最近在学shiro,觉得入门程序还是有用的,记下来防止遗忘,也可供大家参考。
package cn.itcast.shiro.authentication; 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; /** * * @author yxf * shiro验证用户的登录 * */ public class AuthenticationTest { //用户登录退出 @Test public void testLoginAndLogout() { //创建securityManager工厂 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-first.ini"); //创建securityManager SecurityManager securityManager = factory.getInstance(); //securityManager设置到当前运行环境中 SecurityUtils.setSecurityManager(securityManager); //SecurityUtils创建一个subject Subject subject = SecurityUtils.getSubject(); //认证提交前准备token UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "111111"); //执行认证提交 try { subject.login(token); } catch (AuthenticationException e) { e.printStackTrace(); } //是否认证通过 boolean flag = subject.isAuthenticated(); System.out.println("是否认证通过:" + flag); //退出操作 subject.logout(); flag = subject.isAuthenticated(); System.out.println("是否认证通过:" + flag); } }
原文地址:https://www.cnblogs.com/haobingshuaike/p/9304135.html
时间: 2024-11-03 00:40:19