Files
rikako-note/spring/Apache Shiro/Apache Shiro QuickStart.md
2023-01-10 21:59:13 +08:00

4.3 KiB
Raw Blame History

Apache Shiro Quick Start

Apache Shiro常用API

获取当前用户

在任何环境中,都可以通过如下代码来获取当前执行的用户:

Subject currentUser = SecurityUtils.getSubject();

设置用户Session

可以通过如下代码获取用户的Shiro Session并可以向Session中设置属性和值设置的值在用户会话期间内都可以使用。
Shiro Session在使用时并不要求当前位于HTTP环境下

Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );

如果当前应用部署于Web环境下那么Shiro Session默认会使用HttpSession但是如果当前应用部署在非Web环境下时Shiro Session会使用其Enterprise Session Management。

通过用户名和密码对用户进行身份认证

通过如下代码可以通过UsernamePasswordToken来对未认证的用户进行身份认证。

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);
}

对身份认证失败的情况进行异常处理

如果在身份认证的过程中失败,可以通过如下代码捕获认证失败抛出的异常,并对异常进行异常处理

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权限可以通过如下代码进行检验

if ( currentUser.hasRole( "schwartz" ) ) {
    log.info("May the Schwartz be with you!" );
} else {
    log.info( "Hello, mere mortal." );
}

检测某用户是否具有某项特定权限

如果要对已经登录的用户执行检测,检测其是否被授予某项特定的前线,可以通过如下方式进行检测。

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中可以检测用户是否对某实例具有特定权限通过如下代码

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();