【Web加密系列:二】shiro框架詳解

1. shiro簡介以及功能描述

Shiro 是 Java 的一個安全框架。目前,使用 Apache Shiro 的人越來越多,因爲它相 當簡單,對比 Spring
Security,可能沒有 Spring Security 做的功能強大,但是在實際工作時 可能並不需要那麼複雜的東西,所以使用小而簡單的
Shiro 就足夠了。

在這裏插入圖片描述

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

2. shiro實現原理理解

在這裏插入圖片描述
也就是說對於我們而言,最簡單的一個 Shiro 應用:
應用代碼通過 Subject 來進行認證和授權,而 Subject 又委託給 SecurityManager; 我們需要給 Shiro 的 SecurityManager 注入 Realm,從而讓 SecurityManager 能得到合法
的用戶及其權限進行判斷。

3. shiro的架構理解

在這裏插入圖片描述
Subject:主體,可以看到主體可以是任何可以與應用交互的“用戶”;
SecurityManager : 相 當 於 SpringMVC 中 的 DispatcherServlet 或 者 Struts2 中的
FilterDispatcher :是 Shiro 的心臟;所有具體的交互都通過 SecurityManager 進行控制;它管理着所有 Subject、且負責進行認證和授權、及會話、緩存的管理。
Authenticator:認證器,負責主體認證的,這是一個擴展點,如果用戶覺得 Shiro 默認的不好,可以自定義實現;其需要認證策略(Authentication Strategy),即什麼情況下算用戶認證通過了;
Authrizer:授權器,或者訪問控制器,用來決定主體是否有權限進行相應的操作;即控制着用戶能訪問應用中的哪些功能;
Realm:可以有 1 個或多個 Realm,可以認爲是安全實體數據源,即用於獲取安全實體的;可以是 JDBC 實現,也可以是 LDAP 實現,或者內存實現等等;由用戶提供;注意:Shiro不知道你的用戶/權限存儲在哪及以何種格式存儲;所以我們一般在應用中都需要實現自己的 Realm;
SessionManager:如果寫過 Servlet 就應該知道 Session 的概念,Session 呢需要有人去管理它的生命週期,這個組件就是 SessionManager;而 Shiro 並不僅僅可以用在 Web 環境,也可以用在如普通的 JavaSE 環境、EJB 等環境;所有呢,Shiro 就抽象了一個自己的 Session來管理主體與應用之間交互的數據;這樣的話,比如我們在 Web 環境用,剛開始是一臺Web 服務器;接着又上了臺 EJB 服務器;這時想把兩臺服務器的會話數據放到一個地方,
這個時候就可以實現自己的分佈式會話(如把數據放到 Memcached 服務器);
SessionDAO:DAO 大家都用過,數據訪問對象,用於會話的 CRUD,比如我們想把 Session保存到數據庫,那麼可以實現自己的 SessionDAO,通過如 JDBC 寫到數據庫;比如想把Session 放到 Memcached 中,可以實現自己的 Memcached SessionDAO;另外 SessionDAO中可以使用 Cache 進行緩存,以提高性能;
CacheManager:緩存控制器,來管理如用戶、角色、權限等的緩存的;因爲這些數據基本
上很少去改變,放到緩存中後可以提高訪問的性能
Cryptography:密碼模塊,Shiro 提高了一些常見的加密組件用於如密碼加密

4. shiro認證功能(Authentication)流程

流程圖:
在這裏插入圖片描述

@Test
public void testHelloworld() {
//1、獲取 SecurityManager 工廠,此處使用 Ini 配置文件初始化 SecurityManager
Factory<org.apache.shiro.mgt.SecurityManager> factory =
new IniSecurityManagerFactory("classpath:shiro.ini");
//2、得到 SecurityManager 實例 並綁定給 SecurityUtils
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到 Subject 及創建用戶名/密碼身份驗證 Token(即用戶身份/憑證)
Subject subject = SecurityUtils.getSubject();
// UsernamePasswordToken 繼承
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
try {
//4、登錄,即身份驗證
subject.login(token);
} catch (AuthenticationException e) {
//5、身份驗證失敗
}
Assert.assertEquals(true, subject.isAuthenticated()); //斷言用戶已經登錄
//6、退出
subject.logout();

1、UsernamePasswordToken 實現HostAuthenticationToken和RemeberAuthenticationToken,HostAuthenticationToken實現AuthenticationToken
2、首先調用 Subject.login(token)進行登錄,其會自動委託給 Security Manager,調用之前必
須通過 SecurityUtils. setSecurityManager()設置;
3、SecurityManager 負責真正的身份驗證邏輯;它會委託給 Authenticator 進行身份驗證;SecurityManager j接口繼承Authenticator、Authrizer、sessionManage接口
4、Authenticator 纔是真正的身份驗證者,Shiro API 中核心的身份認證入口點,此處可以自
定義插入自己的實現;
5、Authenticator 可能會委託給相應的 AuthenticationStrategy 進行多 Realm 身份驗證,默認
ModularRealmAuthenticator 會調用 AuthenticationStrategy 進行多 Realm 身份驗證;
6、Authenticator 會把相應的 token 傳入 Realm,從 Realm 獲取身份驗證信息,如果沒有返
回/拋出異常表示身份驗證失敗了。此處可以配置多個 Realm,將按照相應的順序及策略進
行訪問。
在這裏插入圖片描述
SecurityManager實現類結構關係。
在這裏插入圖片描述

Realm
在這裏插入圖片描述
一般繼承 AuthorizingRealm(授權)即可;其繼承了 AuthenticatingRealm(即身份驗證),而且也間接繼承了 CachingRealm(帶有緩存實現),重寫裏面AuthenticationInfo 認證和doGetAuthorizationInfo授權方法。

5. shiro授權實現的方式以及流程

  • 基於角色的訪問控制(隱式角色)
  • 基於資源的訪問控制(顯示角色)
    實現方式:
// 1. 編程式(單個和多個角色)
subject.hasRole(“admin”), Array.aslist("admin1","admin2");

//2. 註解
@RequiresRoles("admin")

//3. 頁面控制
<shiro:hasRole name="admin">

//4. shiro配置文件中配置
 <property name="filterChainDefinitions">
            <value>
                /commons/** = anon
                /plugins/** = anon
                /assets/** = anon
                /css/** = anon
                /js/** = anon
                /img/** = anon
                /fonts/** = anon
                /bootstrap/** = anon
                /login = anon
                /interface/** = anon
                /** = user
                
            </value>
</property>

shiro 攔截器規則:

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
實現流程:
在這裏插入圖片描述
在這裏插入圖片描述

6. shiro集成spring框架代碼實現

引入的shiro-All jar包

        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all  shiro-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.4.0</version>
            <type>pom</type>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.ehcache/ehcache  緩存-->
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.6.0</version>
        </dependency>

在web.xml中配置shiroFilter

<filter>
<filter-name>shiroFilter</filter-name>
<!--通過代理設置,有spring 創建交由servlet管理 -->
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
 <!--表示用bean 的生命週期由servlet管理 -->
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
 <!--表示spring中bean的id,若不配置,改屬性默認和filter-name一致-->
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
  • 添加spring-shiro.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- 定義shiro安全管理器,並配置需要實現的功能-->
    <bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
   <!--實現realm功能-->
   <property name="shiroRealm"   ref="shiroRealm"/>
    <!--實現cacheManager功能-->
    <property name="cacheManager" ref="cacheManager"/>
     <!--實現seeionManager功能-->
    <property name="sessionManager" ref="sessionManager"/>
    <!--實現記住我功能-->
    <property name="remeberMe"  ref="remeberMe"/>
    </bean>


<!-- 定義自己實現的realm域,並配置憑證匹配器-->
    <bean id="shiroRealm" class="com.entity.ShiroRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>

<!-- 配置shiro過濾器-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <property name="loginUrl" value="/login"/>
    <property name="successUrl" value="/index"/>
    <property name="unauthorizedUrl" value="/unauth"/>
    <property name="filterChainDefinitions">
        <value>
            /commons/** = anon
            /plugins/** = anon
            /assets/** = anon
            /css/** = anon
            /js/** = anon
            /img/** = anon
            /fonts/** = anon
            /bootstrap/** = anon
            /index = user           <!--user表示用remeberMe功能-->
            /login = anon           <!--登錄頁面可以匿名訪問 -->
            /interface/** = anon     <!--anon表示可以匿名訪問-->
            /logout=logout          <!--登出功能 -->
            /** = user
        </value>
    </property>



</bean>

    <!--配置logout登出管理,id只能爲logout,並且在shiro攔截器中需要定義lgout-->
    <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <property name="redirectUrl" value="/login"/>
    </bean>

<!--實現cacha緩存,讀取ehcache配置文件-->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    <property name="cacheManagerConfigFile" value="classpath:config/ehcache.xml"/>
    </bean>

 <!--配置session管理器-->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="globalSessionTimeout" ref="300000"/>
        <property name="deleteInvalidSessions" value="true"/>
    </bean>

    <!--設置記住我-->
    <bean id="remeberMe" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
    <property name="cookie" ref="remeberMeCookies"/>
    </bean>

<!-- cookis配置-->
    <bean id="remeberMeCookies"  class="org.apache.shiro.web.servlet.SimpleCookie">
        <!--設置最大存活時間和cookie名稱-->
        <property name="maxAge" value="604800"/>
        <property name="name" value="remeberMe"/>
    </bean>

    <!--開啓shiro權限註解功能,並配置securityManager屬性-->
    <aop:config proxy-target-class="true"></aop:config>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>


<!--定義憑證匹配器,也就是對密碼進行算法加密和次數-->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="md5"/>
        <property name="hashIterations" value="2"/>
    </bean>

<!--配置ahtuc過濾器(表單域名稱),在頁面中賬號和密碼的name屬性的值必須和下面定義的相同-->
    <bean id ="authc" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
        <property name="usernameParam" value="username"/>
        <property name="passwordParam" value="password"/>
        <property name="rememberMeParam" value="remeberMe"/>
    </bean>


    <!--異常處理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings" >
 <props>
<!--認證異常和授權異常 -->
     <prop key="org.apache.shiro.authz.UnauthenticatedException">login</prop>
     <prop key="org.apache.shiro.authz.UnauthorizedException">refuse</prop>
 </props>
        </property>

    </bean>


    <!-- 保證實現了Shiro內部lifecycle函數的bean執行,另一種實現註解的方式 -->
  <!--  <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    &lt;!&ndash; AOP式方法級權限檢查 &ndash;&gt;
    <bean
            class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
            depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="false" />
    </bean>
    &lt;!&ndash; 啓用shrio授權註解攔截方式 &ndash;&gt;
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>-->
</beans>
  • ehcache配置文件
<ehcache>
    <!-- 指定一個目錄:當 EHCache 把數據寫到硬盤上時, 將把數據寫到這個目錄下.-->
    <diskStore path="d:\\tempDirectory"/>
    <!-- 設置緩存的默認數據過期策略 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
    />
    <!--
        設定具體的命名緩存的數據過期策略。每個命名緩存代表一個緩存區域
        緩存區域(region):一個具有名稱的緩存塊,可以給每一個緩存塊設置不同的緩存策略。
        如果沒有設置任何的緩存區域,則所有被緩存的對象,都將使用默認的緩存策略。即:<defaultCache.../>
        Hibernate 在不同的緩存區域保存不同的類/集合。
         對於類而言,區域的名稱是類名。如:com.atguigu.domain.Customer
         對於集合而言,區域的名稱是類名加屬性名。如com.atguigu.domain.Customer.orders
    -->
    <!--
        name: 設置緩存的名字,它的取值爲類的全限定名或類的集合的名字
        maxElementsInMemory: 設置基於內存的緩存中可存放的對象最大數目

        eternal: 設置對象是否爲永久的, true表示永不過期, 此時將忽略timeToIdleSeconds 和 timeToLiveSeconds屬性; 默認值是false
       timeToIdleSeconds:設置對象空閒最長時間,以秒爲單位, 超過這個時間,對象過期。當對象過期時,EHCache會把它從緩存中清除。如果此值爲0,表示對象可以無限期地                  處於空閒狀態。
        timeToLiveSeconds:設置對象生存最長時間,超過這個時間,對象過期。如果此值爲0,表示對象可以無限期地存在於緩存中.
                該屬性值必須大於或等於 timeToIdleSeconds 屬性值

        overflowToDisk:設置基於內存的緩存中的對象數目達到上限後,是否把溢出的對象寫到基於硬盤的緩存中
    -->
    <cache name="com.atguigu.hibernate.entities.Employee"
           maxElementsInMemory="1"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           overflowToDisk="true"
    />
    <cache name="com.atguigu.hibernate.entities.Department.emps"
           maxElementsInMemory="1000"
           eternal="true"
           timeToIdleSeconds="0"
           timeToLiveSeconds="0"
           overflowToDisk="false"
    />
</ehcache>
  • 用戶實體類 (實現Serializable)
public class StudentDTO implements Serializable {
    private String stuNo; //學生學號
    private String stuName; //名字
    private String stuAge; //年齡
    private  String cno; //課程號
    private  String score; //分數
    private String stuGender;//性別
    private String password; //密碼
    private String salt; //密碼加密鹽
    /** 更新時間 */
    private Date modifyDate;

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuAge() {
        return stuAge;
    }

    public void setStuAge(String stuAge) {
        this.stuAge = stuAge;
    }

    public String getStuGender() {
        return stuGender;
    }

    public void setStuGender(String stuGender) {
        this.stuGender = stuGender;
    }

    public String getCno() {
        return cno;
    }

    public void setCno(String cno) {
        this.cno = cno;
    }

    public String getScore() {
        return score;
    }

    public void setScore(String score) {
        this.score = score;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }
}
  • 自定義的ShiroRealm域
    @Autowired
    StudentService studentService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

 
        // 從 principals獲取主身份信息,將getPrimaryPrincipal方法返回值轉爲真實身份類型(在上邊的doGetAuthenticationInfo認證通過填充到SimpleAuthenticationInfo中身份類型),
        String userName = (String) principalCollection.getPrimaryPrincipal()
        
        // 根據身份信息獲取權限信息,模擬從數據庫獲取到數據
        List<String> permissions = new ArrayList<String>();
        permissions.add("user:create");// 用戶的創建
        permissions.add("items:add");// 商品添加權限
      
        // 查到權限數據,返回授權信息(要包括 上邊的permissions)
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 將上邊查詢到授權信息填充到simpleAuthorizationInfo對象中
        simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //從authenticationToken獲取用戶名
        StudentDTO un = studentService.getStudentDTOBystuNo(token.getUsername());
        // 賬號不存在
        if (un == null) {
            return null;
        }
        //去認證
        return new SimpleAuthenticationInfo(un, un.getPassword(), ByteSource.Util.bytes(un.getSalt()),getName());
    }


    //清理緩存方法
    public void clearCache(){
        Subject subject= SecurityUtils.getSubject();
        //獲得用戶信息,並清除
        super.clearCache(subject.getPrincipals());
    }
}
  • 常用的權限註解

@RequiresAuthentication
表示當前 Subject 已經通過 login 進行了身份驗證;即 Subject. isAuthenticated()返回 true
@RequiresUser
表示當前 Subject 已經身份驗證或者通過記住我登錄的。
@RequiresGuest
表示當前 Subject 沒有身份驗證或通過記住我登錄過,即是遊客身份
@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)
表示當前 Subject 需要角色 admin 和 user。
@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR)
表示當前 Subject 需要權限 user:a 或 user:b

  • shiro 框架controller實現
@SystemControllerLog(operatePoint=OperatePointConstants.LOGIN, operateType=OperateTypeConstants.LOGIN)
   @PostMapping("/login")
   @CsrfToken(remove = true)
   @ResponseBody
   public Object loginPost(String username, String password) {
       logger.info("POST請求登錄");


       if (StringUtils.isBlank(username)) {
           return renderError("用戶名不能爲空");
       }
       if (StringUtils.isBlank(password)) {
           return renderError("密碼不能爲空");
       }else{
       password = SymmetricEncoder.encryptStr(secretkey, password);
        LOGGER.info(password);
       }
       Subject user = SecurityUtils.getSubject();
       UsernamePasswordToken token = new UsernamePasswordToken(username,password);
       Result result=new Result();
       try {
           user.login(token);                                                                                                                                                          //在這一步跳入入自己實現的域即shiroDbRealm中驗證
           return renderSuccess();
       } catch (UnknownAccountException e) {
       result.setMsg("賬號不存在");
       return result;
           /*throw new RuntimeException("賬號不存在!", e);*/
       } catch (DisabledAccountException e) {
       result.setMsg("賬號未啓用");
       return result;
           /*throw new RuntimeException("賬號未啓用", e);*/
       } catch (IncorrectCredentialsException e) {
       result.setMsg("密碼錯誤,請重試");
       return result;
           /*throw new RuntimeException("密碼錯誤,請重試", e);*/
       } catch (Throwable e) {
       result.setMsg("未知錯誤,請聯繫管理員");
       return result;
          throw new RuntimeException("未知錯誤,請聯繫管理員", e);
       }
      
   }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章