spring與shiro整合
阿新 • • 發佈:2018-07-16
web.xml map life servle cti 我認 ref init for
spring與shiro整合
(1)加入所需要是jar包
(2)配置shiro Filter(web.xml)
<!-- shiro過慮器,DelegatingFilterProxy通過代理模式將spring容器中的bean和filter關聯起來 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <!-- 設置true由servlet容器控制filter的生命周期 --> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> <!-- 設置spring容器filter的bean id,如果不設置則找與filter-name一致的bean--> <init-param> <param-name>targetBeanName</param-name> <param-value>shiroFilter</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3、添加applicationContext-shiro.xml
<!-- Shiro 的Web過濾器 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <!-- loginUrl認證提交地址,如果沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證 --> <property name="loginUrl" value="/login.action" /> <property name="unauthorizedUrl" value="/refuse.jsp" /> <!-- 過慮器鏈定義,從上向下順序執行,一般將/**放在最下邊 --> <property name="filterChainDefinitions"> <value> <!-- 退出攔截,請求logout.action執行退出操作 --> /logout.action = logout <!-- 無權訪問頁面 --> /refuse.jsp = anon <!-- roles[XX]表示有XX角色才可訪問 --> /item/list.action = roles[item],authc /js/** anon /images/** anon /styles/** anon /validatecode.jsp anon /item/* authc <!-- user表示身份認證通過或通過記住我認證通過的可以訪問 --> /** = authc </value> </property> </bean> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="userRealm" /> </bean> <!-- 自定義 realm --> <bean id="userRealm" class="cn.ssm.realm.CustomRealm1"> </bean>
4、自定義realm
public class CustomRealm1 extends AuthorizingRealm { protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { } protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { }
5、添加匹配器認證(applicationContext-shiro.xml)
<!-- 憑證匹配器 --> <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="md5" /> <property name="hashIterations" value="1" /> </bean> <!-- 自定義 realm --> <bean id="userRealm" class="cn.ssm.realm.CustomRealm1"> <property name="credentialsMatcher" ref="credentialsMatcher" /> </bean>
6、shiro註解配置權限(springmvc.xml)
<!-- 開啟aop,對類代理 --> <aop:config proxy-target-class="true"></aop:config> <!-- 開啟shiro註解支持 --> <bean class=" org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean>
spring與shiro整合