摘要:Spring 為優秀多層 J2EE 框架,但本身無安全支援。Acegi 基於 Spring IoC/AOP 實現安全框架。本文探討 Acegi 組件交互,擴展資料庫設計實現 Spring 應用安全控制。
關鍵字:Spring、Acegi、認證、授權
網路應用安全成熱門議題。Spring 以 IoC(控制反轉)與 AOP(面向切面)降低耦合、提升彈性,廣受歡迎。但缺乏安全方案。Acegi 開源安全框架填補空白,將安全服務以 AOP 切面發布,支援聲明式安全控制。
三者交互圖:
原設計過簡:users{username,password,enabled}、authorities{username,authority}。引入 Role (角色) 與 Resource (資源) 概念:
ER 圖:
配置 DataSource、JdbcDaoImpl、密碼編碼器 (MD5)、使用者快取、DaoAuthenticationProvider、ProviderManager。配置片段:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property> ...
</bean>
<bean id="jdbcDaoImpl" class="org.acegisecurity.providers.dao.jdbc.JdbcDaoImpl">
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
<bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.Md5PasswordEncoder"/>
<bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="authenticationDao"><ref local="jdbcDaoImpl"/></property>
<property name="passwordEncoder"><ref local="passwordEncoder"/></property> ...
</bean>
<bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
<property name="providers"><list><ref local="daoAuthenticationProvider"/></list></property>
</bean>
授權管理器配置類似。
URL 資源採 FilterSecurityInterceptor (Servlet Filter);方法級採 MethodSecurityInterceptor (Spring AOP)。
配置 Acegi Servlet Filter 鏈 (6 個 filter,順序固定) 於 web.xml,核心 SecurityEnforcementFilter 做最終存取決定。Spring applicationContext.xml 配置攔截器:
<bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
<property name="authenticationManager"><ref bean="authenticationManager"/></property>
<property name="accessDecisionManager"><ref bean="accessDecisionManager"/></property>
<property name="objectDefinitionSource"><ref local="filterObjectDefinitionSource"/></property>
</bean>
<bean id="filterObjectDefinitionSource" class="org.xiaohongli.acegi.db.DBFilterObjectDefinitionSource">
<constructor-arg><ref bean="jdbcTemplate"/></constructor-arg>
</bean>
DBFilterObjectDefinitionSource 繼承 PathBasedFilterInvocationDefinitionMap,從資料庫讀取受保護 URL;同理 DBMethodObjectDefinitionSource 讀取受保護方法。
Spring 應用普及使安全控制研究重要。Acegi 提供支援但原生範例不足應付複雜權限,本文擴展資料庫設計滿足需求。非 Spring 系統整合 Acegi 待進一步研究。