Java學習筆記-全棧-web開發-23-Shiro框架


1. 功能簡介

  • Authentication:身份認證/登錄,驗證用戶是不是擁有相應的身份;
  • Authorization:授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用 戶是否能進行什麼操作,如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶 對某個資源是否具有某個權限;
  • Session Manager:會話管理,即用戶登錄後就是一次會話,在沒有退出之前,它的所有 信息都在會話中;會話可以是普通 JavaSE 環境,也可以是 Web 環境的;
  • Cryptography:加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲;
  • Web Support:Web 支持,可以非常容易的集成到Web 環境;
  • Caching:緩存,比如用戶登錄後,其用戶信息、擁有的角色/權限不必每次去查,這樣可 以提高效率;
  • Concurrency:Shiro 支持多線程應用的併發驗證,即如在一個線程中開啓另一個線程,能把權限自動傳播過去;
  • Testing:提供測試支持;
  • Run As:允許一個用戶假裝爲另一個用戶(如果他們允許)的身份進行訪問;
  • Remember Me:記住我,這個是非常常見的功能,即一次登錄後,下次再來的話不用登錄了

2. Shiro架構

對外部而言:

在這裏插入圖片描述

  • Subject:應用代碼直接交互的對象是 Subject,也就是說 Shiro 的對外 API 核心就是 Subject。Subject 代表了當前“用戶”, 這個用戶不一定 是一個具體的人,與當前應用交互的任何東西都是 Subject,如網絡爬蟲, 機器人等;與 Subject 的所有交互都會委託給 SecurityManager; Subject 其實是一個門面,SecurityManager 纔是實際的執行者;
  • SecurityManager:安全管理器;即所有與安全有關的操作都會與 SecurityManager 交互;且其管理着所有 Subject;可以看出它是 Shiro 的核心,它負責與 Shiro 的其他組件進行交互,它相當於 SpringMVC 中 DispatcherServlet 的角色
  • Realm:Shiro 從 Realm 獲取安全數據(如用戶、角色、權限),就是說 SecurityManager 要驗證用戶身份,那麼它需要從 Realm 獲取相應的用戶 進行比較以確定用戶身份是否合法;也需要從 Realm 得到用戶相應的角色/ 權限進行驗證用戶是否能進行操作;可以把 Realm 看成 DataSource

對內部而言

在這裏插入圖片描述

  • Subject:任何可以與應用交互的用戶
  • SecurityManager :相當於SpringMVC 中的 DispatcherServlet;是 Shiro 的心臟; 所有具體的交互都通過 SecurityManager 進行控制;它管理着所有 Subject、且負責進 行認證、授權、會話及緩存的管理。
  • Authenticator:負責 Subject 認證,是一個擴展點,可以自定義實現;可以使用認證策略(Authentication Strategy),判斷什麼情況下算用戶認證通過了
  • Authorizer:授權器、即訪問控制器,用來決定主體是否有權限進行相應的操作;即控制着用戶能訪問應用中的哪些功能
  • Realm:可以有 1 個或多個 Realm,可以認爲是安全實體數據源,即用於獲取安全實體的;可以是JDBC 實現,也可以是內存實現等等;由用戶提供;所以一般在應用中都需要實現自己的 Realm;
  • SessionManager:管理 Session 生命週期的組件;而 Shiro 並不僅僅可以用在 Web 環境,也可以用在如普通的 JavaSE 環境
  • CacheManager:緩存控制器,來管理如用戶、角色、權限等的緩存的;因爲這些數據基本上很少改變,放到緩存中後可以提高訪問的性能
  • Cryptography:密碼模塊,Shiro 提高了一些常見的加密組件用於如密碼加密/解密。

3. HelloWorld

官方HelloWorld

public class Quickstart {

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


    public static void main(String[] args) {

        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        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);
    }
}

個人入坑步驟(springboot)

整合方案
1.導入依賴

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.5.0</version>
</dependency>

2.構建數據庫和Javabean

  • 權限

    • 在這裏插入圖片描述
  • 角色

    • 在這裏插入圖片描述
  • 用戶

    • 在這裏插入圖片描述

然後創建對應數據表,除去Javabean中的set類型字段。
在這裏插入圖片描述

儘管是一對多關係,但是爲了顯示清晰,我們使用中間表關聯關係。

mapper查找用戶,並返回他的角色以及權限

<select id="getUserByUsernameAndPsw" resultMap="user">
        select
            u.*,
            r.*,
            p.*
        from user u
        left join user_role ur
        on ur.user_id=u.id
        left join role r
        on ur.role_id=r.rid
        left join role_permi rp
        on rp.role_id=r.rid
        left join permission p
        on rp.permi_id=p.pid
        where u.username=#{username} and u.psw=#{psw}
    </select>

    <resultMap id="user" type="com.example.demo.web.entity.User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <collection property="roles" resultMap="role"/>
    </resultMap>
    <resultMap id="role" type="com.example.demo.web.entity.Role">
        <id column="rid" property="id"/>
        <result column="role_name" property="roleName"/>
        <collection property="permissions" ofType="com.example.demo.web.entity.Permission">
            <id column="pid" property="id"/>
            <result column="permission_name" property="permissionName"/>
        </collection>
    </resultMap>

MD5加密

在這裏插入圖片描述

4. 與Web集成

Shiro 提供了與 Web 集成的支持,其通過一個ShiroFilter 入口來攔截需要安全控制的URL,然後進行相應的控制

ShiroFilter 類似於如 Strut2/SpringMVC 這種 web 框架的前端控制器,是安全控制的入口點,其負責讀取配置(如ini 配置文件),然後判斷URL是否需要登錄/權限等工作

ShiroFilter工作原理

在這裏插入圖片描述

部分細節

  • DelegatingFilterProxy 作用是自動到 Spring 容器查找名字爲 shiroFilter(filter-name)的 bean 並把所有 Filter 的操作委託給它。
  • [urls] 部分的配置,其格式是: “url=攔截器[參數],攔截 器[參數]”;
  • 如果當前請求的 url 匹配 [urls] 部分的某個 url 模式,將會 執行其配置的攔截器。
  • anon(anonymous) 攔截器表示匿名訪問(即不需要登錄即可訪問)
  • authc (authentication)攔截器表示需要身份認證通過後才能訪問

Shiro默認的過濾器

在這裏插入圖片描述

URL匹配

匹配模式

  • url 模式使用 Ant 風格模式
  • Ant 路徑通配符支持 ?、*、**,注意通配符匹配不包括目錄分隔符“/”:
    • ?:匹配一個字符,如 /admin? 將匹配 /admin1,但不匹配 /admin 或 /admin/;
    • *:匹配零個或多個字符串,如 /admin 將匹配 /admin、 /admin123,但不匹配 /admin/1;
    • **:匹配路徑中的零個或多個路徑,如 /admin/** 將匹 配 /admin/a 或 /admin/a/b

匹配順序

  • URL 權限採取第一次匹配優先的方式,即從頭開始使用第一個匹配的 url 模式對應的攔截器鏈。 如:
    • /bb/**=filter1
    • /bb/aa=filter2
    • /**=filter3
  • 如果請求的url是“/bb/aa”,因爲按照聲明順序進行匹 配,那麼將使用 filter1 進行攔截。

5. 整合緩存

使用springboot的緩存starter

pom

<!--整合shiro緩存-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.5.0</version>
        </dependency>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" dynamicConfig="false">
    <diskStore path="java.io.tmpdir"/>

    <cache name="users"
           timeToLiveSeconds="300"
           maxEntriesLocalHeap="1000"/>

    <!--
        name:緩存空間名稱。
        maxElementsInMemory:緩存最大個數。
        eternal:對象是否永久有效,一但設置了,timeout將不起作用。
        timeToIdleSeconds:設置對象在失效前的允許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。
        timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
        overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
        diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩衝區。
        maxElementsOnDisk:硬盤最大緩存個數。
        diskPersistent:是否緩存虛擬機重啓期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
        diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
        memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)。
        clearOnFlush:內存數量最大時是否清除。
    -->
    <defaultCache name="defaultCache"
                  maxElementsInMemory="10000"
                  eternal="false"
                  timeToIdleSeconds="120"
                  timeToLiveSeconds="120"
                  overflowToDisk="false"
                  maxElementsOnDisk="100000"
                  diskPersistent="false"
                  diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU"/>
</ehcache>

ShiroConfig.java

/**
     * 緩存管理器
     * @return
     */
    @Bean
    public EhCacheManager ehCacheManager(){
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
        return cacheManager;
    }
/**
     * 開啓註解模式,aop代理
     * @return
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

/**
 * 自定義realm
 *
 * @return
 */
@Bean
public UserRealm userRealm() {
    UserRealm userRealm = new UserRealm();
    userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
    userRealm.setCacheManager(ehCacheManager());
    return userRealm;
}

/**
 * 安全管理器注入緩存
 */
@Bean
public DefaultWebSecurityManager securityManager() {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(userRealm());
    securityManager.setCacheManager(ehCacheManager());
    return securityManager;
}

EhcacheConfig

package com.bigdata.dangjian.web.config;

import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author sxuer
 */
@Configuration
public class EhcacheConfig {
    /**
     * 設置爲共享模式
     * @return
     */
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setShared(true);
        return cacheManagerFactoryBean;
    }
}

給realm類的service添加懶加載

UserRealm裏注入的SysUserService等service,需要延遲注入,所以都要添加@Lazy註解(如果不加需要自己延遲注入),否則會導致該service裏的@Cacheable緩存註解、@Transactional事務註解等失效。

public class UserRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    IUserService userService;

    /**
     * 如果權限更改了,調用清理緩存
     */
    public void clearCache() {
        Subject currentUser = SecurityUtils.getSubject();
        super.clearCache(currentUser.getPrincipals());
    }

此時僅僅是緩存了權限認整,如果要對mybatis緩存,在對應方法/類上加

@CacheConfig(cacheNames = {"users"})
@Cacheable

視頻臨時筆記

在這裏插入圖片描述在這裏插入圖片描述subject.login(token)的token,傳遞給了reaml(繼承AuthenticatingReaml的類的AuthenticationInfo方法中)

在這裏插入圖片描述
權限註解生成了代理對象,如果使用springAOP,也是通過代理實現的;
由於不允許代理的代理(會出現類型轉換異常),因此,不要在AOP的地方進行shiro註解

Shiro session能夠在service層獲取session

setLoginUrl 設置的是控制器路徑

調用login,進入AuthenticationInfo進行認證
在這裏插入圖片描述在這裏插入圖片描述

個人總結

  • Shiro在web主要用於登錄認證和授權
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章