1. 程式人生 > >《伸手系列》第一集-Shiro安全認證框架的從入門到“出門”

《伸手系列》第一集-Shiro安全認證框架的從入門到“出門”

<?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-3.0.xsd"
       default-lazy-init="true">

    <description>Shiro</description>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
        <property name="realm" ref="authRealm"/>
        <!-- 二級快取 -->
        <property name="cacheManager" ref="shiroEhcacheManager"/>
    </bean>

    <!-- 自定義許可權認證 -->
    <bean id="authRealm" class="cn.itcast.jk.shiro.AuthRealm">
		<property name="userService" ref="userService"/>
		<!--property name="credentialsMatcher" ref="credentialsMatcher"/-->
	</bean>
	
	<!-- 設定密碼加密策略 -->
	<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
		<property name="hashAlgorithmName" value="MD5"/>
	</bean>

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/index.jsp"></property>
        <!-- 沒有許可權或者失敗後跳轉的頁面 -->
        <property name="successUrl" value="/home.action"></property>
        <property name="filterChainDefinitions">
            <!-- , roles[admin], perms[document:read]-->
            <value>
				/index.jsp* = anon
				/home* = anon
				/sysadmin/login/login.jsp* = anon
				/sysadmin/login/logout.jsp* = anon
				/login* = anon
				/logout* = anon
				
				/*.* = authc
				/resource/** = anon
            </value>
        </property>
    </bean>

    <!-- 使用者授權/認證資訊Cache, 採用EhCache  快取 -->
    <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
    </bean>

    <!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- 生成代理,通過代理進行控制 -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true"/>
    </bean>
    
    <!-- 安全管理器 -->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

</beans>

5、自定義realm AuthRealm

在認證、授權內部實現機制中都有提到,最終處理都將交給Real進行處理。因為在Shiro中,最終是通過Realm來獲取應用程式中的使用者、角色及許可權資訊的。通常情況下,在Realm中會直接從我們的資料來源中獲取Shiro需要的驗證資訊。可以說,Realm是專用於安全框架的DAO.