1. 程式人生 > >我的shiro之旅: 三 淺談shiro的filter

我的shiro之旅: 三 淺談shiro的filter

部落格已移至 http://blog.gogl.top

前段時間比較懶,專案也有些緊,沒有寫什麼東西。現在再對Shiro做一些整理。上一篇主要介紹了一個完整而又簡單的shiro整合到專案的例子,主要是spring專案。這篇文章,想談一下關於shiro的filter,這需要讀者對shiro有一定的理解,至少有用過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="/home" />
		<property name="unauthorizedUrl" value="/unauthorized" />
		<!-- The 'filters' property is usually not necessary unless performing 
			an override, which we want to do here (make authc point to a PassthruAuthenticationFilter 
			instead of the default FormAuthenticationFilter: -->
		<!-- <property name="filters">
			<map>
				<entry key="authc">
					<bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" />
				</entry>
			</map>
		</property> -->
		<property name="filterChainDefinitions">
			<value>
				/admin = authc,roles[admin]
				/edit = authc,perms[admin:edit]
				/home = user
				/** = anon
			</value>
		</property>
	</bean>

從上面的配置我們可以看到,當用戶沒有登入的時候,會重發一個login請求,引導使用者去登入。當然,這個login請求做些什麼工作,引導使用者去那裡,完全由開發者決定。successUrl是當用戶登入成功,重發home請求,引導使用者到主頁。unauthorizedUrl指如果請求失敗,重發/unauthorized請求,引導使用者到認證異常錯誤頁面。

		<property name="filters">
			<map>
				<entry key="authc">
					<bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" />
				</entry>
			</map>
		</property>
<property name="filters"> <map> <entry key="authc"> <bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" /> </entry> </map> </property>

把PassThruAuthenticationFilter新增別名為authc,這時/admin請求會交給PassThruAuthenticationFilter處理,替換了原來由

FormAuthenticationFilter來處理。

由此一來,如果有些特殊的請求需要特殊處理,就可以自己寫一個filter,新增一個別名,如:

		<property name="filters">
			<map>
				<entry key="new">
					<bean class="org.xx.xx.NewFilter" />
				</entry>
			</map>
		</property><property name="filters">
			<map>
				<entry key="new">
					<bean class="org.xx.xx.NewFilter" />
				</entry>
			</map>
		</property>

請求用/new = new,這樣/new請求交由NewFilter來處理。