1. 程式人生 > >shiro許可權控制(一):shiro介紹以及整合SSM框架

shiro許可權控制(一):shiro介紹以及整合SSM框架

 shiro安全框架是目前為止作為登入註冊最常用的框架,因為它十分的強大簡單,提供了認證、授權、加密和會話管理等功能 。

  shiro能做什麼?

       認證:驗證使用者的身份

       授權:對使用者執行訪問控制:判斷使用者是否被允許做某事

       會話管理:在任何環境下使用 Session API,即使沒有 Web 或EJB 容器。

       加密:以更簡潔易用的方式使用加密功能,保護或隱藏資料防止被偷窺

       Realms:聚集一個或多個使用者安全資料的資料來源

       單點登入(SSO)功能。

       為沒有關聯到登入的使用者啟用 "Remember Me“ 服務

  Shiro 的四大核心部分

      Authentication(身份驗證):簡稱為“登入”,即證明使用者是誰。

      Authorization(授權):訪問控制的過程,即決定是否有許可權去訪問受保護的資源。

      Session Management(會話管理):管理使用者特定的會話,即使在非 Web 或 EJB 應用程式。

      Cryptography(加密):通過使用加密演算法保持資料安全

  shiro的三個核心元件:     

      Subject :正與系統進行互動的人,或某一個第三方服務。所有 Subject 例項都被繫結到(且這是必須的)一個SecurityManager 上。

      SecurityManager:Shiro 架構的心臟,用來協調內部各安全元件,管理內部元件例項,並通過它來提供安全管理的各種服務。當 Shiro 與一個 Subject 進行互動時,實質上是幕後的 SecurityManager 處理所有繁重的 Subject 安全操作。

      Realms :本質上是一個特定安全的 DAO。當配置 Shiro 時,必須指定至少一個 Realm 用來進行身份驗證和/或授權。Shiro 提供了多種可用的 Realms 來獲取安全相關的資料。如關係資料庫(JDBC),INI 及屬性檔案等。可以定義自己 Realm 實現來代表自定義的資料來源。

  shiro整合SSM框架:

      1.加入 jar 包:以下jar包自行百度下載

      

      2.配置 web.xml 檔案

在web.xml中加入以下程式碼—shiro過濾器。

複製程式碼
<filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
複製程式碼

      3.在 Spring 的配置檔案中配置 Shiro

      Springmvc配置檔案中:

複製程式碼
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
複製程式碼

      Spring配置檔案中匯入shiro配置檔案:

<!-- 包含shiro的配置檔案 -->
          <import resource="classpath:applicationContext-shiro.xml"/>

      新建applicationContext-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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 配置快取管理器 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <!-- 指定 ehcache 的配置檔案,下面會給到 -->
        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
    </bean>

    <!-- 配置進行授權和認證的 Realm,要新增一個java類來實現,下面會有,class=包名.類名,init-methood是初始化的方法 -->
    <bean id="myRealm"
        class="shiro.MyRealm"
        init-method="setCredentialMatcher"></bean>

    <!-- 配置 Shiro 的 SecurityManager Bean. -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="realm" ref="myRealm"/>
    </bean>
    
    <!-- 配置 Bean 後置處理器: 會自動的呼叫和 Spring 整合後各個元件的生命週期方法. -->
    <bean id="lifecycleBeanPostProcessor" 
        class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- 配置 ShiroFilter bean: 該 bean 的 id 必須和 web.xml 檔案中配置的 shiro filter 的 name 一致  -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 裝配 securityManager -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 配置登陸頁面 -->
        <property name="loginUrl" value="/index.jsp"/>
        <!-- 登陸成功後的一面 -->
        <property name="successUrl" value="/shiro-success.jsp"/>
        <property name="unauthorizedUrl" value="/shiro-unauthorized.jsp"/>
        <!-- 具體配置需要攔截哪些 URL, 以及訪問對應的 URL 時使用 Shiro 的什麼 Filter 進行攔截.  -->
        <property name="filterChainDefinitions">
            <value>
                <!-- 配置登出: 使用 logout 過濾器 -->
                /shiro-logout = logout
                /shiro-* = anon
                /user.jsp = roles[user]
                /admin.jsp = roles[admin]
                /** = authc
            </value>
        </property>
    </bean>

</beans>
複製程式碼

     匯入ehcache-shiro.xml配置檔案:

複製程式碼
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<!-- EhCache XML configuration file used for Shiro spring sample application -->
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

If the path is a Java System Property it is replaced by
its value in the running VM.

The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir/shiro-spring-sample"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
    the CacheManager.

    The following attributes are required:

    maxElementsInMemory            - Sets the maximum number of objects that will be created in memory
    eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the
                                     element is never expired.
    overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
                                     has reached the maxInMemory limit.

    The following attributes are optional:
    timeToIdleSeconds              - Sets the time to idle for an element before it expires.
                                     i.e. The maximum amount of time between accesses before an element expires
                                     Is only used if the element is not eternal.
                                     Optional attribute. A value of 0 means that an Element can idle for infinity.
                                     The default value is 0.
    timeToLiveSeconds              - Sets the time to live for an element before it expires.
                                     i.e. The maximum time between creation time and when an element expires.
                                     Is only used if the element is not eternal.
                                     Optional attribute. A value of 0 means that and Element can live for infinity.
                                     The default value is 0.
    diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
                                     The default value is false.
    diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
                                     is 120 seconds.
    memoryStoreEvictionPolicy      - Policy would be enforced upon reaching the maxElementsInMemory limit. Default
                                     policy is Least Recently Used (specified as LRU). Other policies available -
                                     First In First Out (specified as FIFO) and Less Frequently Used
                                     (specified as LFU)
    -->

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />

    <!-- We want eternal="true" (with no timeToIdle or timeToLive settings) because Shiro manages session
expirations explicitly.  If we set it to false and then set corresponding timeToIdle and timeToLive properties,
ehcache would evict sessions without Shiro's knowledge, which would cause many problems
(e.g. "My Shiro session timeout is 30 minutes - why isn't a session available after 2 minutes?"
Answer - ehcache expired it due to the timeToIdle property set to 120 seconds.)

diskPersistent=true since we want an enterprise session management feature - ability to use sessions after
even after a JVM restart.  -->
    <cache name="shiro-activeSessionCache"
           maxElementsInMemory="10000"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="600"/>

    <cache name="org.apache.shiro.realm.SimpleAccountRealm.authorization"
           maxElementsInMemory="100"
           eternal="false"
           timeToLiveSeconds="600"
           overflowToDisk="false"/>

</ehcache>
複製程式碼

      到這一步,配置檔案都基本準備好了,接下來要寫Realm方法了,新建shiro包,在包下新建MyRealm.java檔案繼承AuthorizingRealm

複製程式碼
package shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import bean.user;
import dao.userdao;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private userdao userdao;    
    String pass;

    /**
     * 授權:
     * 
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();        
        Object principal = principalCollection.getPrimaryPrincipal();//獲取登入的使用者名稱    
        if("admin".equals(principal)){               //兩個if根據判斷賦予登入使用者許可權
            info.addRole("admin");
        }
        if("user".equals(principal)){
            info.addRole("list");
        }
        
        info.addRole("user");
        
        return info;
    }

    /*
     * 使用者驗證
     * 
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {   
        //1. token 中獲取登入的 username! 注意不需要獲取password.
        Object principal = token.getPrincipal();
                
        //2. 利用 username 查詢資料庫得到使用者的資訊. 
        user user=userdao.findbyname((String) principal);
        if(user!=null){
            pass=user.getPass();
        }
        String credentials = pass;
        //3.設定鹽值 ,(加密的調料,讓加密出來的東西更具安全性,一般是通過資料庫查詢出來的。 簡單的說,就是把密碼根據特定的東西而進行動態加密,如果別人不知道你的鹽值,就解不出你的密碼)
        String source = "abcdefg";
        ByteSource credentialsSalt = new Md5Hash(source);
   
        
        //當前 Realm 的name
        String realmName = getName();
        //返回值例項化
        SimpleAuthenticationInfo info = 
                new SimpleAuthenticationInfo(principal, credentials, 
                        credentialsSalt, realmName);
        
        return info;
    }

    //init-method 配置. 
    public void setCredentialMatcher(){
        HashedCredentialsMatcher  credentialsMatcher = new HashedCredentialsMatcher();    
        credentialsMatcher.setHashAlgorithmName("MD5");//MD5演算法加密
        credentialsMatcher.setHashIterations(1024);//1024次迴圈加密      
        setCredentialsMatcher(credentialsMatcher);
    }
    
    
    //用來測試的算出密碼password鹽值加密後的結果,下面方法用於新增使用者新增到資料庫操作的,我這裡就直接用main獲得,直接資料庫添加了,省時間
    public static void main(String[] args) {
        String saltSource = "abcdef";    
        String hashAlgorithmName = "MD5";
        String credentials = "passwor";
        Object salt = new Md5Hash(saltSource);
        int hashIterations = 1024;            
        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);
    }

}
複製程式碼

     好了,接下來我們寫一個簡單的action來通過shiro登入驗證。

複製程式碼
//登入認證
    @RequestMapping("/shiro-login")
    public String login(@RequestParam("username") String username, 
            @RequestParam("password") String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);        
        try {
            //執行認證操作. 
            subject.login(token);
        }catch (AuthenticationException ae) {
            System.out.println("登陸失敗: " + ae.getMessage());
            return "/index";
        }
        
        return "/shiro-success";
    }