1. 程式人生 > >shiro許可權框架__由淺入深 1

shiro許可權框架__由淺入深 1

1、實現思路:工廠啟動時載入 .ini檔案許可權、使用者、角色資訊到一個集合中
2、通過 工廠獲取 SecurityManager 元件
3、通過 SecurityUtils.getSubject(); 獲取使用者元件
Subject:應用程式碼直接互動的物件是 Subject,也就是說 Shiro 的對外API 核心就是 Subject
4、Subject 中獲取session
5、subject 是操作入口 currentUser.isAuthenticated() 認證
currentUser.login(token) 登入\currentUser.hasRole(“schwartz”) 角色
currentUser.isPermitted(“user:delete:zhangsan”) 許可權
currentUser.logout(); 退出登入

SecurityManager:安全管理器;即所有與安全有關的操作都會與SecurityManager 互動;且其管理著所有 Subject;可以看出它是 Shiro的核心,
它負責與 Shiro 的其他元件進行互動,它相當於 SpringMVC 中DispatcherServlet 的角色(任務排程中心)、
SecurityManager中的元件_____Session Manager:會話管理,即使用者登入後就是一次會話,在沒有退出之前,它的所有資訊都在會話中即使用者登入後就是一次會話,在沒有退出之前,它的所有資訊都在會話中

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

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
#使用者 密碼 角色1,角色2
# -----------------------------------------------------------------------------
# Roles with assigned permissions

[roles]
#針對上面的角色 有什麼許可權呢,可以做什麼 有什麼權利
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*

goodguy = user:delete:zhangsan

在這裡插入圖片描述

public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

       Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

       SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        // 獲取當前的 Subject. 呼叫 SecurityUtils.getSubject();
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        // 測試使用 Session 
        // 獲取 Session: Subject#getSession()
        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 + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        // 測試當前的使用者是否已經被認證. 即是否已經登入. 
        // 調動 Subject 的 isAuthenticated() 
        if (!currentUser.isAuthenticated()) {
        	// 把使用者名稱和密碼封裝為 UsernamePasswordToken 物件
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            // rememberme
            token.setRememberMe(true);
            try {
            	// 執行登入. 
                currentUser.login(token);
            } 
            // 若沒有指定的賬戶, 則 shiro 將會丟擲 UnknownAccountException 異常. 
            catch (UnknownAccountException uae) {
                log.info("----> There is no user with username of " + token.getPrincipal());
                return; 
            } 
            // 若賬戶存在, 但密碼不匹配, 則 shiro 會丟擲 IncorrectCredentialsException 異常。 
            catch (IncorrectCredentialsException ice) {
                log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
                return; 
            } 
            // 使用者被鎖定的異常 LockedAccountException
            catch (LockedAccountException lae) {
                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:
        //print their identifying principal (in this case, a username):
        log.info("----> User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        // 測試是否有某一個角色. 呼叫 Subject 的 hasRole 方法. 
        if (currentUser.hasRole("schwartz")) {
            log.info("----> May the Schwartz be with you!");
        } else {
            log.info("----> Hello, mere mortal.");
            return; 
        }

        //test a typed permission (not instance-level)
        // 測試使用者是否具備某一個行為. 呼叫 Subject 的 isPermitted() 方法。 
        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.");
        }

        //a (very powerful) Instance Level permission:
        // 測試使用者是否具備某一個行為. 
        if (currentUser.isPermitted("user:delete:zhangsan")) {
            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!");
        }

        //all done - log out!
        // 執行登出. 呼叫 Subject 的 Logout() 方法. 
        System.out.println("---->" + currentUser.isAuthenticated());
        
        currentUser.logout();
        
        System.out.println("---->" + currentUser.isAuthenticated());

        System.exit(0);
    }

借鑑:https://blog.csdn.net/qq_20641565/article/details/78772938

由上述流程可以推測,spring整合shiro後流程如下:

spring容器\bean工廠啟動時  
			載入ShiroFilter 的 bean 中資訊進入map
			認證、授權 bean__繼承_AuthorizingRealm  得到許可權set<string>
			
	web.xml中對每一次請求進行攔截 
			//如果沒有認證__會跳轉到自定義登入頁、那些訪問資源可以直接訪問
			//每一次請求時會比對
			//登入只會執行一次
			//許可權認證__每一次請求都會執行、得到許可權set  根據頁面的shiro標籤實現顯示、隱藏-------------