4、Spring Security 安全權(quán)限管理手冊_第1頁
4、Spring Security 安全權(quán)限管理手冊_第2頁
4、Spring Security 安全權(quán)限管理手冊_第3頁
4、Spring Security 安全權(quán)限管理手冊_第4頁
4、Spring Security 安全權(quán)限管理手冊_第5頁
已閱讀5頁,還剩20頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

SpringSecurity3.0安全權(quán)限管理手冊參考文獻(xiàn):1、中的springsecurity權(quán)限管理手冊。2、springsecurity3.0權(quán)限管理手冊3、spring的相關(guān)資料。本文檔內(nèi)容僅僅作為公司權(quán)限管理資料用,對于企業(yè)來說,權(quán)限管理將是系統(tǒng)中的非常重要的一個(gè)模塊,權(quán)限的設(shè)計(jì)也是參考相關(guān)資料進(jìn)行整理和補(bǔ)充。系統(tǒng)將通過數(shù)據(jù)庫進(jìn)行管理用戶權(quán)限。權(quán)限管理搭建要的問題:1、區(qū)分Authentication(驗(yàn)證)與Authorization(授權(quán))驗(yàn)證這個(gè)用戶是誰?用戶身份可靠嗎?授權(quán)某用戶A是否可以訪問資源R某用戶A是否可以執(zhí)行M操作某用戶A是否可以對資源R執(zhí)行M操作2、SS中的驗(yàn)證特點(diǎn)支持多種驗(yàn)證方式支持多種加密格式支持組件的擴(kuò)展和替換可以本地化輸出信息3、SS中的授權(quán)特點(diǎn)支持多種仲裁方式支持組件的擴(kuò)展和替換支持對頁面訪問、方法訪問、對象訪問的授權(quán)。4、SS核心安全實(shí)現(xiàn)Web安全通過配置ServletFilter激活SS中的過濾器鏈實(shí)現(xiàn)Session一致性驗(yàn)證實(shí)現(xiàn)免登陸驗(yàn)證(Remember-Me驗(yàn)證)提供一系列標(biāo)簽庫進(jìn)行頁面元素的安全控制方法安全通過AOP模式實(shí)現(xiàn)安全代理Web安全與方法安全均可以使用表達(dá)式語言定義訪問規(guī)則5、配置SS配置Web.xml,應(yīng)用安全過濾器配置Spring,驗(yàn)證與授權(quán)部分在web頁面中獲取用戶身份在web頁面中應(yīng)用安全標(biāo)簽庫實(shí)現(xiàn)方法級安全6、配置web.xml7、Spring配置文件中設(shè)置命名空間8、通過數(shù)據(jù)庫驗(yàn)證用戶身份9、完善web頁面驗(yàn)證規(guī)則10、自定義驗(yàn)證配置11、本地化消息輸出(國際化)根據(jù)公司項(xiàng)目的開發(fā)要求和集合springsecurity3.0功能,公司將通過數(shù)據(jù)庫進(jìn)行對用戶身份驗(yàn)證和授權(quán),系統(tǒng)將建立5個(gè)基礎(chǔ)表進(jìn)行對權(quán)利的管理。第一部分?jǐn)?shù)據(jù)庫設(shè)計(jì)1、表設(shè)計(jì)表1:用戶表(pubusers)序號字段類型含義備注1UserIdVchar(32)用戶idPK2user_accountVchar(30)登陸用戶名(登陸號)3UsernameVchar(40)用戶姓名4userPasswordVchar(100)用戶密碼5EnabledInt是否被禁用0禁用1正常6isSysInt是否是超級用戶0非1是7userDEScVchar(100)描述說明:pubusers表中的登錄名和密碼用來控制用戶的登錄。表2:權(quán)限表(pubauthorities)序號字段類型含義備注1authorityIdVchar(32)權(quán)限idPK2AuthoritynameVchar(40)權(quán)限名稱3AuthorityDEScVchar(100)權(quán)限描述4EnabledInt是否被禁用0禁用1正常5isSysInt是否是超級權(quán)限0非1是說明:pub_authorities表中描述的是系統(tǒng)擁有哪些權(quán)限,如果要詳細(xì)分類,可亦將一個(gè)url定義一個(gè)權(quán)限,那樣就能對所有資源進(jìn)行管理。表3:角色表(pubroles)序號字段類型含義備注1roleIdVchar(32)角色idPK2rolenameVchar(100)角色名稱3roleDEScVchar(100)角色描述4EnabledInt是否被禁用0禁用1正常5isSysInt是否是超級權(quán)限0非1是說明:pub_roles表中描述的是系統(tǒng)按用戶分類或按照功能模塊分類,將系統(tǒng)進(jìn)

行整合歸類管理。表4:資源表(pubresources)序號字段類型含義備注1resourceIdVchar(32)資源idPK2resource_nameVchar(lOO)資源名稱3resourcetypeVchar(40)資源類型url、method4priorityint資源優(yōu)先權(quán)即排序5resourcestringVchar(200)資源鏈接6resourceDEScVchar(100)資源描述7EnabledInt是否被禁用0禁用1正常8isSysInt是否是超級權(quán)限0非1是說明:pubroles表中描述的是系統(tǒng)需要保?護(hù)的資源及(url或方法)。以上四個(gè)表是權(quán)限管理的基礎(chǔ)表(用戶表、權(quán)限表、角色表、資源表)。表5:用戶角色連接表(pubusersroles)序號字段類型含義備注1IdIndetityId主鍵PK2userIdVchar(32)用戶id3roleidVchar(32)角色id說明:用來定管理用戶和角色的關(guān)系。表6:角色權(quán)限連接表(pubrolesauthorities)序號字段類型含義備注1IdIndetityId主鍵PK2roleIdVchar(32)角色id3authorityIdVchar(32)權(quán)限id說明:用來定管理角色和權(quán)限的關(guān)系。表7:權(quán)限資源連接表(pubauthoritiesresources)序號字段類型含義備注1IdIndetityId主鍵PK2authorityIdVchar(32)權(quán)限id3resourceIdVchar(32)資源id說明:用來定管理角色和權(quán)限的關(guān)系。2、建表語句如下(數(shù)據(jù)庫釆用MSSQL2000):createtablepub_users(user_idvarchar(32),user_accountvarchar(30),user_namevarchar(40),user_passwordvarchar(100),user_descvarchar(100),enabledint,issysint);altertablepub_usersaddconstraintpk_pub_usersprimarykey(user_id);createtablepub_authorities(authority_idvarchar(32),authority_namevarchar(40),authority_descvarchar(100),enabledint,issysint);altertablepub_authoritiesaddconstraintpk_pub_authoritiesprimarykey(authority_id);createtablepub_roles(role_idvarchar(32),role_namevarchar(40),role_descvarchar(100),enabledint,issysint);altertablepub_rolesaddconstraintpk_pub_rolesprimarykey(role_id);createtablepub_resources(resource_idvarchar(32),resource_namevarchar(100),resource_descvarchar(100),resource_typevarchar(40),resource_stringvarchar(200),priorityint,enabledint,issysint);altertablepub_resourcesaddconstraintpk_pub_resourcesprimarykey(resource_id);createtablepub_users_roles(idnumeric(12,0)IDENTITYNOTNULL,user_idvarchar(32),role_idvarchar(32),enabledint);altertablepub_users_rolesaddconstraintpk_pub_users_rolesprimarykey(id);altertablepub_users_rolesaddconstraintfk_users_roles_usersforeignkey(user_id)referencespub_users(user_id);altertablepub_users_rolesaddconstraintfk_users_roles_rolesforeignkey(role_id)referencespub_roles(role_id);createtablepub_roles_authorities(idnumeric(12,0)IDENTITYNOTNULL,role_idvarchar(32),authority_idvarchar(32),enabledint);altertablepub_roles_authoritiesaddconstraintpk_pub_roles_authoritiesprimarykey(id);altertablepub_roles_authoritiesaddconstraintfk_pub_roles_authorities_authoritiesforeignkey(authority_id)referencespub_authorities(authority_id);altertablepub_roles_authoritiesaddconstraintfk_pub_roles_authorities_rolesforeignkey(role_id)referencespub_roles(role_id);createtablepub_authorities_resources(idnumeric(12,0)IDENTITYNOTNULL,authority_idvarchar(32),resource_idvarchar(32),enabledint);altertablepub_authorities_resourcesaddconstraintpk_pub_authorities_resourcesprimarykey(id);altertablepub_authorities_resourcesaddconstraintfk_pub_authorities_resources_authoritiesforeignkey(authority_id)referencespub_authorities(authority_id);altertablepub_authorities_resourcesaddconstraintfk_pub_authorities_resources_resourcesforeignkey(resource_id)referencespub_resources(resource_id);3、E-R圖如下:

Jpiib_authnritiesiutharity_i1authority_nsmfii^th-arily_d.<:GC?rio.bla>ipubusETSrolespub_roles_au.thnrpubanthnritiesresourcesutflr_3dGitablwdaiLtK:>rity_^bL昱dAutRar1七『_】drqeoutJpiib_authnritiesiutharity_i1authority_nsmfii^th-arily_d.<:GC?rio.bla>ipubusETSrolespub_roles_au.thnrpubanthnritiesresourcesutflr_3dGitablwdaiLtK:>rity_^bL昱dAutRar1七『_】drqeoutaG_idqjiqBLad.pub^rol■usarztiiTic:,2EgibLad■usaren&lilelUSSl_f>i££lVpubUSETSUEbTACCDUIltras:^rrefl_racourcflnuTiores■:Hji-ca■laeg■:4切p。res■:Hji-castringpri■:>rity亡:rtXbl亡dissyzpubTesoiircps第二部分WEB數(shù)據(jù)庫整合提示:相關(guān)代碼請參考項(xiàng)目模塊1、將數(shù)據(jù)庫表結(jié)構(gòu)和Hibernate建立映射,本系統(tǒng)釆用annotation進(jìn)行對數(shù)據(jù)庫進(jìn)行零配置處理(請參考hibernate映射),如圖。-甘_、rstfr:anie-借0--jJcom.rstcu.±r:±jtie3JBrriijdill&eIII-田屈十;擊currirTiun■…田seem-ity+護(hù)址田.lataisA田fentit7E"JT|FubAn^horities.javaTOC\o"1-5"\h\z!i:i:"r-...-^田…!FubAnthoritiezRezowceE.java!i!ii*1—.^j?-JFubRewrnrreez.ja^a!j:!:I—.^;PubRol&e.ja^a:::j:'i—4-.IPubRijl&EAutkorLties.java::=::S|—.^"E".jLF口bl『sers.j十iIjFubU5ersEol已5.java2、建立權(quán)限的Dao層。FubAutkorLtiesTl:=lFubAutkorLtiesTl:=lu.iavaFubAuthjjri_ti已sResuui-ce5Dao.javaFutiTieeijurc@illam.jav:±FutiJLijlgsAuthoritiesllam.javaPubEdleeBao.」:羽注PublJserzH:=lu.」a^aPublJsersFlolesDao.j-口3r51Erame-?繆srcis-fflcom.rstcu.fr:inie+?III._-母£)■rTiOduly5pul-;吾se'-ixrity-JB訕+++++++FubAutkorLti總弓Ustj:lV=lPubAuthorl11esReeoiji-ceeDao.javaFublk弓iirceslia'?.javaFutifLijlesAuthoritiezllam.javaFutiJLijlgsBao.jaLraPublJserzH:=lu.」a^aPublJsersFlolesDao.j一亡廿rettr:iirieEJ-j_^src丨H-fflcoti.retca.fr:inie+田module5_田PuP+電common_審eecirrity-田皿+0::::;C十31iiii十國+0|||+0I!:!:+』!!:!:j—t+』3、建立權(quán)限的Service層4、配置web.xml<?xmlversion="1.0"encoding="UTF-8"?><web-appversion="2.5"xmlns="/xml/ns/javaee<web-appversion="2.5"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><display-name>rstframe</display-name><context-param><param-name>webAppRootKey</param-name><param-value>rstframe.root</param-value></context-param><context-param><param-name>log4jConfigLocation</param-name><param-value>classpath:perties</param-value></context-param><context-param><param-name>log4jRefreshInterval</param-name><param-value>60000</param-value></context-param><!--SpringApplicationContext配置文件的路徑,可使用通配符,多個(gè)路徑用,號分隔此參數(shù)用于后面的SpringContextLoader--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:/applicationContext.xml,classpath*:/applicationContext-rstframe.xml</param-value></context-param><!--CharacterEncodingfilter--><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!--Springside'sHibernateOpenSessionInViewfilter--><filter><filter-name>hibernateOpenSessionInViewFilter</filter-name><filter-class>com.rstco.frame.modules.orm.hibernate.OpenSessionInViewFilter</filter-class><init-param><param-name>excludeSuffixs</param-name><param-value>js,css,jpg,gif</param-value></init-param></filter><filter-mapping><filter-name>hibernateOpenSessionInViewFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!--SpringSecurityfilter--><filter><filter-name>springSecurityFilterChain</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping><filter-name>springSecurityFilterChain</filter-name><url-pattern>/*</url-pattern></filter-mapping><!--Struts2filter,actionPackages--><filter><filter-name>struts2Filter</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2Filter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!--Spring的ApplicationContext載入--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener><!--Spring刷新Introspector防止內(nèi)存泄露--><listener><listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class></listener><!--防止多人登陸,控制一個(gè)用戶只能登錄一次,不能在其他地方重新登錄--><listener><listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class></listener><!—session超時(shí)定乂,單位為分鐘—><session-config><session-timeout>20</session-timeout></session-config><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!--error><error><exception-type>java.lang.Throwable</exception-type><location>/common/500jsp</location></error><error><error-code>500</error-code><location>/common/500jsp</location></error><error><error-code>404</error-code><location>/common/404jsp</location></error><error><error-code>403</error-code><location>/common/403jsp</location></error><jsp-config><taglib><taglib-uri>/WEB-INF/struts-menu-el.tld</taglib-uri><taglib-location>/WEB-INF/tlds/struts-menu-el.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/struts-menu.tld</taglib-uri><taglib-location>/WEB-INF/tlds/struts-menu.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/c.tld</taglib-uri><taglib-location>/WEB-INF/tlds/c.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/fmt.tld</taglib-uri><taglib-location>/WEB-INF/tlds/fmt.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/fn.tld</taglib-uri><taglib-location>/WEB-INF/tlds/fn.tld</taglib-location></taglib><!--loushangtld--><taglib><taglib-uri>/WEB-INF/web-date.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-date.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-flex.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-flex.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-graph.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-graph.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-grid.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-grid.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-html.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-html.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-list.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-list.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-loushang.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-loushanq.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-menu.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-menu.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-multitab.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-multitab.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-seltree.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-seltree.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-tab.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-tab.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-tree.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-tree.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-widgets.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-widgets.tld</taglib-location></taglib><taglib><taglib-uri>/WEB-INF/web-i18n.tld</taglib-uri><taglib-location>/WEB-INF/tlds/web-i18n.tld</taglib-location></taglib><!--loushangend--><taglib><taglib-uri>/WEB-INF/gystudio.tld</taglib-uri><taglib-location>/WEB-INF/tlds/gystudio.tld</taglib-location></taglib></jsp-config><mime-mapping><extension>rar</extension><mime-type>application/rar</mime-type></mime-mapping></web-app>5、配置springsecurity3.0中的xml文件文件名:applicationContext-security.xml<?xmlversion="1.0"encoding="UTF-8"?><beans:beansxmlns="/schema/security"xmlns:beans="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.0.xsd/schema/security/schema/security/spring-security-3.0.xsd"><beans:description>SpringSecurity安全配置</beans:description><!--http安全配置一_><httpauto-config="true"><intercept_urlpattern="/css/**"filters="none"/><intercept_urlpattern="/images/**"filters="none"/><intercept-urlpattern="/js/**"filters="none"/><intercept-urlpattern="/login.jsp"filters="none"/><!--<intercept-urlpattern="/index.jsp"access="ROLE_USER"/><intercept-urlpattern="/main.jsp"access="ROLE_ADAMIN"/>--><form-loginlogin="/login.jsp"default-target-url="/index.jspauthentication-failure-url="/login.jsp?error=1"/><!--嘗試訪問沒有權(quán)限的頁面時(shí)跳轉(zhuǎn)的頁面--><access-denied-handlererror="/common/403.jsp"/><logoutlogout-success-url="/login.jsp"/><session-management><concurrency-controlmax-sessions="1"error-if-maximum-exceeded="true"/></session-management><!--增加一個(gè)filter,這點(diǎn)與Acegi是不一樣的,不能修改默認(rèn)的filter了,這個(gè)filter位于FILTER_SECURITY_INTERCEPTOR之前一一><custom-filterref="myFilter"before="FILTER_SECURITY_INTERCEPTOR"/></http><!--一個(gè)自定義的filter,必須包含authenticationManager,accessDecisionManager,securityMetadataSource三個(gè)屬性,我們的所有控制將在這三個(gè)類中實(shí)現(xiàn),解釋詳見具體配置--><beans:beanid="myFilter"class="erceptor.MyFilterSecurityInterceptor"><beans:propertyname="authenticationManager"ref="authenticationManager"/><beans:propertyname="accessDecisionManager"ref="myAccessDecisionManagerBean"/><beans:propertyname="securityMetadataSource"ref="mySecurityMetadataSource"/></beans:bean><!--驗(yàn)證配置,認(rèn)證管理器,實(shí)現(xiàn)用戶認(rèn)證的入口,主要實(shí)現(xiàn)UserDetailsService接口即可--><authentication-manageralias="authenticationManager"><authentication-provideruser-service-ref="userDetailsService"><!--<s:password-encoderhash="sha"/>--></authentication-provider></authentication-manager><!--項(xiàng)目實(shí)現(xiàn)的用戶查詢服務(wù),將用戶信息查詢出來--><beans:beanid="userDetailsService"class="com.rstco.frame.pub.security.support.MyUserDetailService"/><!--訪問決策器,決定某個(gè)用戶具有的角色,是否有足夠的權(quán)限去訪問某個(gè)資源--><beans:beanid="myAccessDecisionManagerBean"class="com.rstco.frame.pub.security.support.MyAccessDecisionManager"></beans:bean><!--資源源數(shù)據(jù)定義,將所有的資源和權(quán)限對應(yīng)關(guān)系建立起來,即定義某一資源可以被哪些角色訪問--><beans:beanid="mySecurityMetadataSource"class="com.rstco.frame.pub.security.support.MyInvocationSecurityMetadataSourceService"></beans:bean><!--定義國際化--><beans:beanid="messageSource"class="org.springframework.context.support.ReloadableResourceBundleMessageSource"><<beans:propertyname="basename"value="classpath:org/springframework/security/messages_zh_CN"/></beans:bean></beans:beans>這是項(xiàng)目的主體部分:-fcpi_s*tr:inie-於src這是項(xiàng)目的主體部分:-fcpi_s*tr:inie-於srcII?0-^5-,:lfri-匕£tcu.fi-!dnieiii.+卑mI:duleE_田put+I■■:f1fB-[廿COfTlfTl<TL另zecirrity亠.打i:i■:-田d.ata田-??出entLty-i^_rinterceptor十.」MyFilterSe匚ui-itylntere?ptor.j:iv:±(j-JJEhFVICt:-ssupportM/IilvocatlonSecurityfdetadataSmui-ceS已M/IilvocatlonSecurityfdetadataSmui-ceS已rvice.javaMyU£erD?taiIServine.jin.strutenuutilswst這四個(gè)類說明如下?!?、用來獲得用戶驗(yàn)證信息〈MyUserDetailService)代碼如下:packagecom.rstco.frame.pub.security.support;importjava.util.ArrayList;importjava.util.Collection;importjava.util.List;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.dao.DataAccessException;importorg.springframework.security.core.GrantedAuthority;importorg.springframework.security.core.userdetails.User;importorg.springframework.security.core.userdetails.UserDetails;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.core.userdetails.UsernameNotFoundException;importorg.springframework.stereotype.Service;importcom.rstco.frame.pub.security.dao.PubAuthoritiesResourcesDao;importcom.rstco.frame.pub.security.dao.PubUsersDao;importcom.rstco.frame.pub.security.entity.PubAuthorities;importcom.rstco.frame.pub.security.entity.PubAuthoritiesResources;//你就可以從數(shù)據(jù)庫中讀入用戶的密碼,角色信息,是否鎖定,賬號是否過期@ServicepublicclassMyUserDetailServiceimplementsUserDetailsService{@AutowiredprivatePubUsersDaopubUsersDao;@AutowiredprivatePubAuthoritiesResourcesDaopubAuthoritiesResourcesDao;publicUserDetailsloadUserByUsername(Stringusername)throwsUsernameNotFoundException,DataAccessException{Collection<GrantedAuthority>auths=newArrayList<GrantedAuthority>();//取得用戶的權(quán)限List<PubAuthorities>auth=pubUsersDao.findAuthByUserName(username);Stringpassword=null;//取得用戶的密碼password=pubUsersDao.findUserByname(username).get(0).getUserPassword();List<PubAuthoritiesResources>aaa=pubAuthoritiesResourcesDao.getAll();Useruser=newUser(username,password,true,true,true,true,auths);returnuser;}}的對應(yīng)資源數(shù)據(jù)二、最核心的地方,就是提供某個(gè)資源對應(yīng)的權(quán)限定義,取得所有角色(auth)的對應(yīng)資源數(shù)據(jù)(MyInvocationSecurityMetadataSourceService代碼如下:packagecom.rstco.frame.pub.security.support;importjava.util.ArrayList;importjava.util.Collection;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjavax.servlet.ServletContext;importorg.hibernate.Query;importorg.hibernate.Session;importorg.hibernate.SessionFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.security.access.ConfigAttribute;importorg.springframework.security.access.SecurityConfig;importorg.springframework.security.web.FilterInvocation;ercept.FilterInvocationSecurityMetadataSource;importorg.springframework.security.web.util.AntUrlPathMatcher;importorg.springframework.security.web.util.UrlMatcher;importorg.springframework.stereotype.Service;importcom.rstco.frame.modules.orm.hibernate.HibernateDao;importcom.rstco.frame.pub.security.dao.PubAuthoritiesResourcesDao;importcom.rstco.frame.pub.security.entity.PubAuthorities;importcom.rstco.frame.pub.security.entity.PubResources;/***最核心的地方,就是提供某個(gè)資源對應(yīng)的權(quán)限定義,即getAttributes方法返回的結(jié)果。注意,我例子中使用的是AntUrlPathMatcher這個(gè)pathmatcher來檢查URL是否與資源定義匹配,*事實(shí)上你還要用正則的方式來匹配,或者自己實(shí)現(xiàn)一個(gè)matcher。*此類在初始化時(shí),應(yīng)該取到所有資源及其對應(yīng)角色的定義**說明:對于方法的spring注入,只能在方法和成員變量里注入,如果一個(gè)類要進(jìn)行實(shí)例化的時(shí)候,不能注入對象和操作對象,所以在構(gòu)造函數(shù)里不能進(jìn)行操作注入的數(shù)據(jù)。*/@ServicepublicclassMyInvocationSecurityMetadataSourceServiceimplementsFilterInvocationSecurityMetadataSource{@AutowiredprivatePubAuthoritiesResourcesDaopubAuthoritiesResourcesDao;privateUrlMatcherurlMatcher=newAntUrlPathMatcher();privatestaticMap<String,Collection<ConfigAttribute>>resourceMap=null;publicMyInvocationSecurityMetadataSourceService(){loadResourceDefine();}/*privatevoidloadResourceDefine(){HashMap<String,resourceMap=newHashMap<String,Collection<ConfigAttribute>>();newnewnewnewArrayList<ConfigAttribute>();ConfigAttributecaSecurityConfig("ROLE_ADMIN");atts.add(ca);resourceMap.put("/index.jsp",atts);resourceMap.put("/i.jsp",atts);}*/privatevoidloadResourceDefine(){ApplicationContextcontext=newClassPathXmlApplicationContext("applicationContext.xml");SessionFactorysessionFactory=(SessionFactory)context.getBean("sessionFactory");Sessionsession=sessionFactory.openSession();List<String>query=session.createSQLQuery("selectauthority_namefrompub_authorities").list();resourceMap=newHashMap<String,Collection<ConfigAttribute>>();Collection<ConfigAttribute>atts=newArrayList<ConfigAttribute>();//List<PubAuthorities>auths=session.createQuery(arg0);//pubAuthoritiesResourcesDao.findAuthAll();for(Stringauth:query){ConfigAttributeca=newSecurityConfig(auth);//"ROLE_ADMIN"http://atts.add(ca);List<String>query1=session.createSQLQuery("selectresource_string"+"fromPub_Authorities_Resources,Pub_Resources,Pub_authorities"+"wherePub_Authorities_Resources.resource_id=Pub_Resources.resource_idand"+〃Pub_Authorities_Resources.resource_id=Pub_authorities.authority_idand"+"Authority_name='"+auth+"'").list();for(Stringres:query1){Stringurl=res;//判斷資源文件和權(quán)限的對應(yīng)關(guān)系,如果已經(jīng)存在,要進(jìn)行增加if(resourceMap.containsKey(url)){Collection<ConfigAttribute>value=resourceMap.get(url);value.add(ca);resourceMap.put(url,value);

//"log.jsp","role_user,role_admin"}else{atts.add(ca);resourceMap.put(url,atts);}resourceMap.put(url,atts);}}}//AccordingtoaURL,FindoutpermissionconfigurationofthisURL.publicCollection<ConfigAttribute>getAttributes(Objectobject)throwsIllegalArgumentException{//guessobjectisaURL.Stringurl=((FilterInvocation)object).getRequestUrl();Iterator<String>ite=resourceMap.keySet().iterator();while(ite.hasNext()){StringresURL=ite.next();if(urlMatcher.pathMatchesUrl(url,resURL)){returnresourceMap.get(resURL);}}returnnull;}publicbooleansupports(Class<?>clazz){returntrue;}publicCollection<ConfigAttribute>getAllConfigAttributes(){returnnull;}}三、最重要的是decide方法,如果不存在對該資源的定義,直接放行;否則,如果找到正確的角色,即認(rèn)為擁有權(quán)限,并放行,否則thrownew就會進(jìn)入上面提到的4O3.jsp頁面。MyAccessDecisionManagerAccessDeniedException("noright");就會進(jìn)入上面提到的4O3.jsp頁面。MyAccessDecisionManager代碼如下:packagecom.rstco.frame.pub.security.support;importjava.util.Collection;importjava.util.Iterator;importorg.springframework.security.access.AccessDecisionManager;importorg.springframework.security.access.AccessDeniedException;importorg.springframework.security.access.ConfigAttribute;importorg.springframework.security.access.SecurityConfig;importorg.springframework.security.authentication.InsufficientAuthenticationException;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.GrantedAuthority;publicclassMyAccessDecisionManagerimplementsAccessDecisionManager{//Inthismethod,needtocompareauthenticationwithconfigAttributes.//1,AobjectisaURL,afilterwasfindpermissionconfigurationbythisURL,andpasstohere.//2,Checkauthenticationhasattributeinpermissionconfiguration(configAttributes)//3,Ifnotmatchcorrespondingauthentication,throwaAccessDeniedException.publicvoiddecide(Authenticationauthentication,Objectobject,Collection<ConfigAttribute>configAttributes)throwsAccessDeniedException,InsufficientAuthenticationException{if(configAttributes==null){return;}System.out.println(object.toString());//objectisaURL.Iterator<ConfigAttribute>ite=configAttributes.iterator();while(ite.hasNext()){ConfigAttributeca=ite.ne

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論