package xue.xiang.yi.demo.shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Demo {
//这里简单说明一下 transient 关键字的作用. 就是序列化的实话,不序列这个对象
private static final transient Logger log = LoggerFactory.getLogger(Demo.class);
public static void main(String[] args) {
log.info("My First Apache Shiro Application");
/*//1. 这个方法已经废弃. 点击去 注释会告诉我们使用 securityManager 代替. 而 DefaultSecurityManager 是它的子类. 我选择的default
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2.
SecurityManager securityManager = factory.getInstance();
//3.
SecurityUtils.setSecurityManager(securityManager); */
//获取本地资源文件,设置realm为本地的资源文件
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
defaultSecurityManager.setRealm(iniRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager);
//获取对象主体
Subject currentUser = SecurityUtils.getSubject();
//获取session
Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );
//判断是否登陆过
if ( !currentUser.isAuthenticated() ) {
//没有登陆. 就登陆
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//this is all you have to do to support 'remember me' (no config - built in!):
token.setRememberMe(true);
try {
currentUser.login( token );
log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}
if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
currentUser.logout();
log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
} catch ( UnknownAccountException e ) {
log.error("用户名不存在", e);
} catch ( IncorrectCredentialsException e ) {
log.error("密码不正确", e);
} catch ( LockedAccountException e ) {
log.error("账户被锁定?", e);
} catch ( AuthenticationException e ) {
log.error("AuthenticationException", e);
}
}
//正常退出
System.exit(0);
}
}
shiro参考官方10分案例编写.废弃过期方法
最新推荐文章于 2023-07-11 20:42:20 发布