【02】10分钟教程
说明
本章节来自于Apache Shiro官网的10分钟教程https://shiro.apache.org/10-minute-tutorial.html,
旨在通过这个简单教程让开发人员知道Shiro是如何在应用程序中使用的。
下载
确保已安装 JDK 1.8+ 和 Maven 3.0.3+
通过以下地址下载Shiro源码
https://www.apache.org/dyn/closer.lua/shiro/1.9.1/shiro-root-1.9.1-source-release.zip
解压,参考其中的samples/quickstart/src/main/java/Quickstart.java
快速入门
获取Subject
在几乎所有环境中,可以通过以下代码获取当前正在执行的用户
Subject currentUser = SecurityUtils.getSubject();
现在既然有了一个Subject
,能用他来做什么呢?
获取Session
Session session = currentUser.getSession();
Session.setAttribute("someKey", "aValue");
注意这个Session
是Shiro中的实例,其不依赖Http环境,即使在非Web环境下也可以使用。
登录
Subject代表当前用户,那么当前用户是谁呢,至少需要登录一次才能知道。
if(!currentUser.isAuthenticated()){ UsernamePasswordToken token = new UsernamepasswordToken("lonestarr", "vespa"); token.setRemeberMe(true); currentUser.login(token); }
登录失败
如果登录失败,可以通过捕获各种特定异常来进行相应的处理
try { currentUser.login( token ); //if no exception, that's it, we're done! } catch ( UnknownAccountException uae ) { //username wasn't in the system, show them an error message? } catch ( IncorrectCredentialsException ice ) { //password didn't match, try again? } catch ( LockedAccountException lae ) { //account for that username is locked - can't login. Show them a message? } ... more types exceptions to check if you want ... } catch ( AuthenticationException ae ) { //unexpected condition - error? }
Shiro内置了多种类型的异常,当然你也可以自定义Shiro中没有的异常,具体参考AuthenticationException JavaDoc
获取登录用户信息
登录成功之后,我们可以通过以下代码获取当前登录用户的详细信息
//print their identifying principal (in this case, a username): 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( "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(); //removes all identifying information and invalidates their session too.