public classQuickstart {private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);public static voidmain(String[] args) {//创建具有配置的领域,用户,角色和权限的Shiro SecurityManager的最简单方法是使用简单的INI配置。//我们将通过使用可以提取.ini文件并返回SecurityManager实例的工厂来做到这一点://在类路径的根目录下使用shiro.ini文件 ,使用工厂生成一个securityManager实例,将提前定义好的shiro.ini文件内容加载进去
Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager=factory.getInstance();//对于这个简单的示例快速入门,使SecurityManager作为JVM单例进行访问。大多数应用程序不这样做,而是依靠其容器配置或web.xml来//webapps。这超出了此简单快速入门的范围,因此我们将只做最少的工作,以便您可以继续对事物有所了解。
SecurityUtils.setSecurityManager(securityManager);//获取当前用户对象, 1.这里的currentUser对象说白了就是一个用户容器,可以用来载入前端输入的真实用户信息
Subject currentUser =SecurityUtils.getSubject();//通过当前用户获取session
Session session =currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value= (String) session.getAttribute("someKey");if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}//判断当前用户是否被认证, 2.这时currentUser还没有载入用户信息,执行isAuthenticated()实现与之前ini定义好的内容进行检索比较,肯定匹配不成功
if (!currentUser.isAuthenticated()) {//Token:令牌 3.把输入的真实用户信息封装到token对象中
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true); //记住我
try{
//4.把token注入currentUser对象的.login()方法中执行登录操作,这里的.login(XXX)方法会将token中的用户信息 // 和shiro.ini定义的用户信息进行匹配,若匹配成功则登录成功,且currentUser也会成为一个真正意义上的用户对象,而不是一个空的用户容器, // 若匹配失败,则会catch 以下种类的异常信息
currentUser.login(token);//执行登录操作
}catch (UnknownAccountException uae) { //4.1用户名不存在的异常
log.info("There is no user with username of " +token.getPrincipal());
}catch (IncorrectCredentialsException ice) { //4.2密码不对的异常
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
}catch (LockedAccountException lae) { //4.3用户被锁定的异常
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}//... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) { //认证异常,上面的异常都是其子类//unexpected condition? error?
}
}//say who they are://打印其标识主体(在这种情况下为用户名)
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");//test a role://判断当前用户是否拥有某种角色
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
}else{
log.info("Hello, mere mortal.");
}//测试用户是否具备某一个行为权限,调用subject的isPermitted()方法(不是实例级别)//粗粒度
if (currentUser.isPermitted("lightsaber:wield")) {
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!");
}//下面三行代码,第二行用于执行用户的退出操作,第一行和第三行用于检验退出操作是否成功