- [Apache Shiro Quick Start](#apache-shiro-quick-start) - [Apache Shiro常用API](#apache-shiro常用api) - [获取当前用户](#获取当前用户) - [设置用户Session](#设置用户session) - [通过用户名和密码对用户进行身份认证](#通过用户名和密码对用户进行身份认证) - [对身份认证失败的情况进行异常处理](#对身份认证失败的情况进行异常处理) - [对已经登录的用户进行role检验](#对已经登录的用户进行role检验) - [检测某用户是否具有某项特定权限](#检测某用户是否具有某项特定权限) - [在实例级别对用户的权限进行检测](#在实例级别对用户的权限进行检测) - [用户登出](#用户登出) # Apache Shiro Quick Start ## Apache Shiro常用API ### 获取当前用户 在任何环境中,都可以通过如下代码来获取当前执行的用户: ```java Subject currentUser = SecurityUtils.getSubject(); ``` ### 设置用户Session 可以通过如下代码获取用户的Shiro Session,并可以向Session中设置属性和值,设置的值在用户会话期间内都可以使用。 **Shiro Session在使用时并不要求当前位于HTTP环境下** ```java Session session = currentUser.getSession(); session.setAttribute( "someKey", "aValue" ); ``` > 如果当前应用部署于Web环境下,那么Shiro Session默认会使用HttpSession,但是如果当前应用部署在非Web环境下时,Shiro Session会使用其Enterprise Session Management。 ### 通过用户名和密码对用户进行身份认证 通过如下代码,可以通过UsernamePasswordToken来对未认证的用户进行身份认证。 ```java if ( !currentUser.isAuthenticated() ) { //collect user principals and credentials in a gui specific manner //such as username/password html form, X509 certificate, OpenID, etc. //We'll use the username/password example here since it is the most common. //(do you know what movie this is from? ;) UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); //this is all you have to do to support 'remember me' (no config - built in!): token.setRememberMe(true); currentUser.login(token); } ``` ### 对身份认证失败的情况进行异常处理 如果在身份认证的过程中失败,可以通过如下代码捕获认证失败抛出的异常,并对异常进行异常处理 ```java 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? } ``` ### 对已经登录的用户进行role检验 如果用户已经登录,如果要检测该用户是否被授予某role权限,可以通过如下代码进行检验 ```java if ( currentUser.hasRole( "schwartz" ) ) { log.info("May the Schwartz be with you!" ); } else { log.info( "Hello, mere mortal." ); } ``` ### 检测某用户是否具有某项特定权限 如果要对已经登录的用户执行检测,检测其是否被授予某项特定的前线,可以通过如下方式进行检测。 ```java 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."); } ``` ### 在实例级别对用户的权限进行检测 在Shiro中,可以检测用户是否对某实例具有特定权限,通过如下代码: ```java 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!"); } ``` ### 用户登出 如果已经登录的用户想要执行登出操作,可以通过如下代码进行登录: ```java currentUser.logout(); ```