shiro(二)——quickstart快速入门
目录:
1.shiro快速入门需要的依赖
<dependencies> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.1</version> </dependency> <!-- configure logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
2.shiro.ini文件
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
[users]下面包含了 (用户名)=(密码),(角色名)
[roles]下面包含了 角色名、对应的权限
3.quickstart.java
public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { //创建具有配置的领域,用户,角色和权限的Shiro SecurityManager的最简单方法是使用简单的INI配置。 //我们将通过使用可以提取.ini文件并返回SecurityManager实例的工厂来做到这一点: //在类路径的根目录下使用shiro.ini文件 ,使用工厂生成一个securityManager实例,将提前定义好的shiro.ini文件内容加载进去 Factory<SecurityManager> 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!"); }
//下面三行代码,第二行用于执行用户的退出操作,第一行和第三行用于检验退出操作是否成功
System.out.println("---->" + currentUser.isAuthenticated());
// 5.currentUser.logout()方法会清空currentUser中session的所有用户信息 currentUser.logout();
System.out.println("---->" + currentUser.isAuthenticated());
System.exit(0);
}
}
以上就是最简单的shiro快速入门,其中shiro.ini用来模拟数据库中存储的用户相关信息,代码中标黄放大的注释表达方式可能比较口语化且意思不一定十分准确,但主要还是为了便于理解,希望对你有所帮助。