天天看點

ShiroWhat文檔簡要分析了解術語架構快速啟動

What

Apache Shiro旨在成為最全面的,但也是最容易使用的Java安全架構。

文檔

沒有比官網更好的了

https://shiro.apache.org/get-started.html

簡要分析

ShiroWhat文檔簡要分析了解術語架構快速啟動

四大基石:認證,授權,會話管理,加密

了解術語

Authentication:認證

Authorization:授權(通路控制)

其他:

https://shiro.apache.org/terminology.html

架構

Shiro的架構有三個主要概念:Subject,SecurityManager和Realms

ShiroWhat文檔簡要分析了解術語架構快速啟動
https://shiro.apache.org/architecture.html

快速啟動

擷取目前使用者(這裡叫主題subject,代之使用者,程式,上下文等,不叫user主要是防止shiro不跟其他架構重名)

Subject currentUser = SecurityUtils.getSubject();

獲得會話session

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

登陸認證

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?
}

獲得目前使用者主體
currentUser.getPrincipal()

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

//是否有權限
if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
    log.info("You may use a lightsaber ring.  Use it wisely.");
} else {
    log.info("Sorry, lightsaber rings are for schwartz masters only.");
}

// 登出

currentUser.logout(); //removes all identifying information and invalidates their session too.