什么时候会用到代理proxy模式?

举一个例子:有两个应用App1和App2,它们都是受Cas服务器保护的,即请求它们时都需要通过Cas 服务器的认证。现在需要在App1中通过Http请求访问App2,显然该请求将会被App2配置的Cas的AuthenticationFilter拦截并转向Cas 服务器,Cas服务器将引导用户进行登录认证,这样我们也就访问不到App2的资源了。针对这种应用场景,Cas也提供了Cas Proxy 轻松的解决了这个问题。

cas server 版本4.1.3

cas clietn版本4.0.0

cas搭建参考:http://www.cnblogs.com/l412382979/p/8818765.html

cas proxy配置参考地址:http://elim.iteye.com/blog/2270446

cas server配置deployerConfigContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!--
  3.  
  4. Licensed to Apereo under one or more contributor license
  5. agreements. See the NOTICE file distributed with this work
  6. for additional information regarding copyright ownership.
  7. Apereo licenses this file to you under the Apache License,
  8. Version 2.0 (the "License"); you may not use this file
  9. except in compliance with the License. You may obtain a
  10. copy of the License at the following location:
  11.  
  12. http://www.apache.org/licenses/LICENSE-2.0
  13.  
  14. Unless required by applicable law or agreed to in writing,
  15. software distributed under the License is distributed on an
  16. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17. KIND, either express or implied. See the License for the
  18. specific language governing permissions and limitations
  19. under the License.
  20.  
  21. -->
  22. <!--
  23. | deployerConfigContext.xml centralizes into one file some of the declarative configuration that
  24. | all CAS deployers will need to modify.
  25. |
  26. | This file declares some of the Spring-managed JavaBeans that make up a CAS deployment.
  27. | The beans declared in this file are instantiated at context initialization time by the Spring
  28. | ContextLoaderListener declared in web.xml. It finds this file because this
  29. | file is among those declared in the context parameter "contextConfigLocation".
  30. |
  31. | By far the most common change you will need to make in this file is to change the last bean
  32. | declaration to replace the default authentication handler with
  33. | one implementing your approach for authenticating usernames and passwords.
  34. +-->
  35.  
  36. <beans xmlns="http://www.springframework.org/schema/beans"
  37. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  38. xmlns:p="http://www.springframework.org/schema/p"
  39. xmlns:c="http://www.springframework.org/schema/c"
  40. xmlns:tx="http://www.springframework.org/schema/tx"
  41. xmlns:util="http://www.springframework.org/schema/util"
  42. xmlns:sec="http://www.springframework.org/schema/security"
  43. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  44. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  45. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
  46. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
  47.  
  48. <!--
  49. | The authentication manager defines security policy for authentication by specifying at a minimum
  50. | the authentication handlers that will be used to authenticate credential. While the AuthenticationManager
  51. | interface supports plugging in another implementation, the default PolicyBasedAuthenticationManager should
  52. | be sufficient in most cases.
  53. +-->
  54. <bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager">
  55. <constructor-arg>
  56. <map>
  57. <!--
  58. | IMPORTANT
  59. | Every handler requires a unique name.
  60. | If more than one instance of the same handler class is configured, you must explicitly
  61. | set its name to something other than its default name (typically the simple class name).
  62. -->
  63. <entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />
  64. <entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />
  65. <!-- key-ref指定自己的本地数据库访问 -->
  66. <entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>
  67. </map>
  68. </constructor-arg>
  69.  
  70. <!-- Uncomment the metadata populator to capture the password.
  71. <property name="authenticationMetaDataPopulators">
  72. <util:list>
  73. <bean class="org.jasig.cas.authentication.CacheCredentialsMetaDataPopulator"/>
  74. </util:list>
  75. </property>
  76. -->
  77.  
  78. <!--
  79. | Defines the security policy around authentication. Some alternative policies that ship with CAS:
  80. |
  81. | * NotPreventedAuthenticationPolicy - all credential must either pass or fail authentication
  82. | * AllAuthenticationPolicy - all presented credential must be authenticated successfully
  83. | * RequiredHandlerAuthenticationPolicy - specifies a handler that must authenticate its credential to pass
  84. -->
  85. <property name="authenticationPolicy">
  86. <bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" />
  87. </property>
  88. </bean>
  89.  
  90. <!-- Required for proxy ticket mechanism. -->
  91. <bean id="proxyAuthenticationHandler"
  92. class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
  93. p:httpClient-ref="supportsTrustStoreSslSocketFactoryHttpClient" p:requireSecure="false"/>
  94.  
  95. <!--
  96. | TODO: Replace this component with one suitable for your enviroment.
  97. |
  98. | This component provides authentication for the kind of credential used in your environment. In most cases
  99. | credential is a username/password pair that lives in a system of record like an LDAP directory.
  100. | The most common authentication handler beans:
  101. |
  102. | * org.jasig.cas.authentication.LdapAuthenticationHandler
  103. | * org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler
  104. | * org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler
  105. | * org.jasig.cas.support.spnego.authentication.handler.support.JCIFSSpnegoAuthenticationHandler
  106. -->
  107. <bean id="primaryAuthenticationHandler"
  108. class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">
  109. <property name="users">
  110. <map>
  111. <entry key="casuser" value="Mellon"/>
  112. </map>
  113. </property>
  114. </bean>
  115.  
  116. <!-- Required for proxy ticket mechanism -->
  117. <bean id="proxyPrincipalResolver"
  118. class="org.jasig.cas.authentication.principal.BasicPrincipalResolver" />
  119.  
  120. <!--
  121. | Resolves a principal from a credential using an attribute repository that is configured to resolve
  122. | against a deployer-specific store (e.g. LDAP).
  123. -->
  124. <bean id="primaryPrincipalResolver"
  125. class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver"
  126. p:principalFactory-ref="principalFactory"
  127. p:attributeRepository-ref="attributeRepository" />
  128.  
  129. <!--
  130. Bean that defines the attributes that a service may return. This example uses the Stub/Mock version. A real implementation
  131. may go against a database or LDAP server. The id should remain "attributeRepository" though.
  132. +-->
  133.  
  134. <bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao">
  135. <constructor-arg index="0" ref="dataSource" />
  136. <constructor-arg index="1" value="select ID_ as id,PASSWORD_ as pwd from USER_TABLE where {0}" />
  137. <property name="queryAttributeMapping">
  138. <map>
  139. <!-- 这里的key需写username和登录页面一致,value对应数据库用户名字段
  140. select ID_ as id from USER_TABLE where USERNAME_=#username#
  141. -->
  142. <entry key="username" value="USERNAME_"/>
  143. </map>
  144. </property>
  145. <property name="resultAttributeMapping">
  146. <map>
  147. <!-- key为对应的数据库字段名称,value为提供给客户端获取的属性名字,系统会自动填充值 -->
  148. <entry key="id" value="id"/>
  149. <entry key="pwd" value="pwd"/>
  150. </map>
  151. </property>
  152. </bean>
  153.  
  154. <bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl"
  155. p:registeredServices-ref="registeredServicesList" />
  156.  
  157. <util:list id="registeredServicesList">
  158. <bean class="org.jasig.cas.services.RegexRegisteredService"
  159. p:id="1"
  160. p:name="HTTPS and IMAPS services on example.com"
  161. p:serviceId="^(https?|imaps?|http?)://.*"
  162. p:evaluationOrder="0" >
  163. <!-- 基于正则表达式匹配代理端,以下这行不加的话代理端会被cas server拒绝 -->
  164. <property name="proxyPolicy">
  165. <bean class="org.jasig.cas.services.RegexMatchingRegisteredServiceProxyPolicy" c:pgtUrlPattern="^https?://.*" />
  166. </property>
  167. </bean>
  168. </util:list>
  169.  
  170. <bean id="auditTrailManager" class="org.jasig.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />
  171.  
  172. <bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor" p:monitors-ref="monitorsList" />
  173.  
  174. <util:list id="monitorsList">
  175. <bean class="org.jasig.cas.monitor.MemoryMonitor" p:freeMemoryWarnThreshold="10" />
  176. <!--
  177. NOTE
  178. The following ticket registries support SessionMonitor:
  179. * DefaultTicketRegistry
  180. * JpaTicketRegistry
  181. Remove this monitor if you use an unsupported registry.
  182. -->
  183. <bean class="org.jasig.cas.monitor.SessionMonitor"
  184. p:ticketRegistry-ref="ticketRegistry"
  185. p:serviceTicketCountWarnThreshold="5000"
  186. p:sessionCountWarnThreshold="100000" />
  187. </util:list>
  188.  
  189. <!-- 访问本地数据库 -->
  190. <bean id="dbAuthHandler"
  191. class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
  192. <property name="dataSource" ref="dataSource"></property>
  193. <property name="sql" value="SELECT PASSWORD_ FROM USER_TABLE WHERE USERNAME_ = ? and ISACTIVE_='Y' "></property>
  194. <property name="passwordEncoder" ref="MD5PasswordEncoder"></property>
  195. </bean>
  196.  
  197. <!-- SSO密码加密配置 -->
  198. <bean id="MD5PasswordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder">
  199. <constructor-arg index="0">
  200. <value>MD5</value>
  201. </constructor-arg>
  202. </bean>
  203.  
  204. <!-- mysql连接 -->
  205. <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  206. <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  207. <property name="url" value="jdbc:mysql://localhost:3306/cas?useUnicode=true&characterEncoding=UTF-8"/>
  208. <property name="username" value="root" />
  209. <property name="password" value="root" />
  210. </bean> -->
  211.  
  212. <!-- oracle连接 -->
  213. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  214. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
  215. <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
  216. <property name="username" value="username" />
  217. <property name="password" value="password" />
  218. </bean>
  219. </beans>

  代理端应用配置(app1)注意:文件中${casClientRoot}和${cas.server.url}在properties文件中配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:s="http://www.springframework.org/schema/security"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. http://www.springframework.org/schema/security
  8. http://www.springframework.org/schema/security/spring-security-3.1.xsd">
  9.  
  10. <!-- <s:http pattern="/saveMyCss.json" security="none" /> -->
  11. <!-- sso -->
  12. <s:http auto-config="true" entry-point-ref="casAuthenticationEntryPoint" servlet-api-provision="true">
  13. <s:intercept-url pattern="/login.jsp" access="ROLE_USER"></s:intercept-url>
  14. <s:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />
  15. <s:custom-filter ref="singleLogoutFilter" before="CAS_FILTER" />
  16. <!-- 增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前-->
  17. <s:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>
  18. <s:custom-filter ref="casAuthenticationFilter" position="CAS_FILTER" />
  19. </s:http>
  20.  
  21. <s:authentication-manager alias="authenticationManager">
  22. <s:authentication-provider ref="casAuthenticationProvider"></s:authentication-provider>
  23. </s:authentication-manager>
  24.  
  25. <!-- http://localhost:8088/SpringSecurity 具体应用 -->
  26. <!-- j_spring_cas_security_check spring的虚拟URL,此标志标识使用 CAS authentication upon return from CAS SSO login. -->
  27. <bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
  28. <property name="service" value="${casClientRoot}j_spring_cas_security_check"></property>
  29. <property name="sendRenew" value="false"></property>
  30. </bean>
  31.  
  32. <!-- 配置ProxyGrantingTicketStorage,用以保存pgtId和pgtIou -->
  33. <bean id="proxyGrantingTicketStorage" class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl"/>
  34.  
  35. <bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
  36. <property name="authenticationManager" ref="authenticationManager" />
  37. <property name="authenticationSuccessHandler" ref="loginSuccess" />
  38. <property name="authenticationFailureHandler" ref="loginFail" />
  39. <!-- 指定处理地址,不指定时默认将会是“/j_spring_cas_security_check” -->
  40. <property name="filterProcessesUrl" value="/j_spring_cas_security_check" />
  41. <!-- 保存cas server传递过来的pgtId和pgtIou -->
  42. <property name="proxyGrantingTicketStorage" ref="proxyGrantingTicketStorage"/>
  43. <!-- 用以指定Cas Server在回调代理端传递pgtId和pgtIou时回调地址相对于代理端的路径 -->
  44. <property name="proxyReceptorUrl" value="/proxyCallback"/>
  45. </bean>
  46.  
  47. <!-- loginUrl cas 服务登录地址 -->
  48. <bean id="casAuthenticationEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
  49. <property name="loginUrl" value="${cas.server.url}login" />
  50. <property name="serviceProperties" ref="serviceProperties" />
  51. </bean>
  52.  
  53. <!-- ticketValidator cas服务验证地址 -->
  54. <bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
  55. <property name="userDetailsService" ref="userDetailServiceImpl" />
  56. <property name="serviceProperties" ref="serviceProperties" />
  57. <!-- 配置TicketValidator在登录认证成功后验证ticket -->
  58. <property name="ticketValidator">
  59. <bean class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator">
  60. <!-- Cas Server访问地址的前缀,即根路径-->
  61. <!-- cas.server.url https://localhost:8888/cas-server/ -->
  62. <constructor-arg index="0" value="${cas.server.url}" />
  63. <!-- 指定Cas Server回调传递pgtId和pgtIou的地址,该地址必须使用https协议 -->
  64. <!-- casClientRoot https://localhost:8080/app1/ -->
  65. <property name="proxyCallbackUrl" value="${casClientRoot}proxyCallback"/>
  66. <property name="proxyGrantingTicketStorage" ref="proxyGrantingTicketStorage"/>
  67. </bean>
  68. </property>
  69. <property name="key" value="key4CasAuthenticationProvider" />
  70. </bean>
  71.  
  72. <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"></bean>
  73.  
  74. <!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性,
  75. 我们的所有控制将在这三个类中实现,解释详见具体配置 -->
  76. <bean id="filterSecurityInterceptor"
  77. class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
  78. <property name="authenticationManager" ref="authenticationManager" />
  79. <property name="accessDecisionManager" ref="dbAccessDecisionManagerBean" />
  80. <property name="securityMetadataSource" ref="securityMetadataSource" />
  81. </bean>
  82.  
  83. <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
  84.  
  85. <bean id="userDetailServiceImpl" class="com.common.security.UserDetailsServiceImpl">
  86. <property name="dao" ref="dao" />
  87. </bean>
  88.  
  89. <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
  90. <bean id="dbAccessDecisionManagerBean" class="com.common.security.DbAccessDecisionManager">
  91. </bean>
  92.  
  93. <!-- 资源源数据定义,即定义某一资源可以被哪些角色访问 -->
  94. <bean id="securityMetadataSource" class="com.common.security.DbInvocationSecurityMetadataSource">
  95. <property name="securityData" ref="securityData" />
  96. </bean>
  97.  
  98. <bean id="securityData" class="com.common.security.SecurityData">
  99. <property name="dao" ref="dao" />
  100. </bean>
  101. <!-- 用户需要登录时跳转的地址 -->
  102. <bean id="authenticationEntryPoint" class="com.common.security.AuthenticationEntryPoint">
  103. <property name="loginFormUrl" value="/loginre.jsp" />
  104. </bean>
  105.  
  106. <!-- 用户登录失败 -->
  107. <bean id="loginFail" class="com.common.security.LoginFail">
  108. <property name="url" value="login.jsp" />
  109. </bean>
  110.  
  111. <!-- 用户登录成功 -->
  112. <bean id="loginSuccess" class="com.common.security.loginSuccess">
  113. <property name="url" value="ire.htm" />
  114. </bean>
  115.  
  116. <!-- 注销客户端 -->
  117. <bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" />
  118.  
  119. <!-- 注销服务器端 -->
  120. <bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
  121. <constructor-arg value="${cas.server.url}logout?service=${casClientRoot}" />
  122. <constructor-arg>
  123. <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
  124. </constructor-arg>
  125. <property name="filterProcessesUrl" value="/j_spring_cas_security_logout" />
  126. </bean>
  127.  
  128. </beans>

  被代理端配置(app2)注意:文件中${casClientRoot}和${cas.server.url}在properties文件中配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:s="http://www.springframework.org/schema/security"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. http://www.springframework.org/schema/security
  8. http://www.springframework.org/schema/security/spring-security-3.1.xsd">
  9.  
  10. <!-- <s:http pattern="/saveMyCss.json" security="none" /> -->
  11. <!-- sso -->
  12. <s:http auto-config="true" entry-point-ref="casAuthenticationEntryPoint" servlet-api-provision="true">
  13. <s:intercept-url pattern="/login.jsp" access="ROLE_USER"></s:intercept-url>
  14. <s:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />
  15. <s:custom-filter ref="singleLogoutFilter" before="CAS_FILTER" />
  16. <!-- 增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前-->
  17. <s:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>
  18. <s:custom-filter ref="casAuthenticationFilter" position="CAS_FILTER" />
  19. </s:http>
  20.  
  21. <s:authentication-manager alias="authenticationManager">
  22. <s:authentication-provider ref="casAuthenticationProvider"></s:authentication-provider>
  23. </s:authentication-manager>
  24.  
  25. <!-- http://localhost:8088/SpringSecurity 具体应用 -->
  26. <!-- j_spring_cas_security_check spring的虚拟URL,此标志标识使用 CAS authentication upon return from CAS SSO login. -->
  27. <bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
  28. <!-- casClientRoot https://localhost:8080/app2/ -->
  29. <property name="service" value="${casClientRoot}j_spring_cas_security_check"></property>
  30. <!-- <property name="sendRenew" value="false" /> -->
  31. <!-- 通过ServiceProperties指定CasAuthenticationFilter的authenticateAllArtifacts为true -->
  32. <property name="authenticateAllArtifacts" value="true"/>
  33. </bean>
  34.  
  35. <bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
  36. <property name="authenticationManager" ref="authenticationManager" />
  37. <property name="authenticationSuccessHandler" ref="loginSuccess" />
  38. <property name="authenticationFailureHandler" ref="loginFail" />
  39. <!-- 指定处理地址,不指定时默认将会是“/j_spring_cas_security_check” -->
  40. <property name="filterProcessesUrl" value="/j_spring_cas_security_check" />
  41. <!-- 通过ServiceProperties指定CasAuthenticationFilter的authenticateAllArtifacts为true -->
  42. <property name="serviceProperties" ref="serviceProperties" />
  43. <!-- 指定使用的AuthenticationDetailsSource为ServiceAuthenticationDetailsSource -->
  44. <property name="authenticationDetailsSource">
  45. <bean class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource" />
  46. </property>
  47. </bean>
  48.  
  49. <!-- loginUrl cas 服务登录地址 -->
  50. <bean id="casAuthenticationEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
  51. <property name="loginUrl" value="${cas.server.url}login" />
  52. <property name="serviceProperties" ref="serviceProperties" />
  53. </bean>
  54.  
  55. <!-- ticketValidator cas服务验证地址 -->
  56. <bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
  57. <property name="userDetailsService" ref="userDetailServiceImpl" />
  58. <property name="serviceProperties" ref="serviceProperties" />
  59. <!-- 配置TicketValidator在登录认证成功后验证ticket -->
  60. <property name="ticketValidator">
  61. <bean class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator">
  62. <!-- Cas Server访问地址的前缀,即根路径-->
  63. <!-- cas.server.url https://localhost:8888/cas-server/ -->
  64. <constructor-arg index="0" value="${cas.server.url}" />
  65. <!-- 如果有多个代理端可以多写几个value -->
  66. <property name="allowedProxyChains">
  67. <value>https://localhost:8080/app1/proxyCallback</value>
  68. </property>
  69. </bean>
  70. </property>
  71. <property name="key" value="key4CasAuthenticationProvider" />
  72. <property name="statelessTicketCache">
  73. <bean class="org.springframework.security.cas.authentication.EhCacheBasedTicketCache">
  74. <!-- Ehcache对象 -->
  75. <property name="cache" ref="proxyTicketCache"/>
  76. </bean>
  77. </property>
  78. </bean>
  79.  
  80. <!-- 定义一个Ehcache -->
  81. <bean id="proxyTicketCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
  82. <property name="cacheName" value="proxyTicketCache" />
  83. <property name="timeToLive" value="600"/>
  84. </bean>
  85.  
  86. <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"></bean>
  87.  
  88. <!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性,
  89. 我们的所有控制将在这三个类中实现,解释详见具体配置 -->
  90. <bean id="filterSecurityInterceptor"
  91. class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
  92. <property name="authenticationManager"
  93. ref="authenticationManager" />
  94. <property name="accessDecisionManager"
  95. ref="dbAccessDecisionManagerBean" />
  96. <property name="securityMetadataSource"
  97. ref="securityMetadataSource" />
  98. </bean>
  99.  
  100. <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
  101.  
  102. <bean id="userDetailServiceImpl" class="com.common.security.UserDetailsServiceImpl">
  103. <property name="dao" ref="dao" />
  104. </bean>
  105.  
  106. <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
  107. <bean id="dbAccessDecisionManagerBean" class="com.common.security.DbAccessDecisionManager">
  108. </bean>
  109.  
  110. <!-- 资源源数据定义,即定义某一资源可以被哪些角色访问 -->
  111. <bean id="securityMetadataSource" class="com.common.security.DbInvocationSecurityMetadataSource">
  112. <property name="securityData" ref="securityData" />
  113. </bean>
  114.  
  115. <bean id="securityData" class="com.common.security.SecurityData">
  116. <property name="dao" ref="dao" />
  117. </bean>
  118. <!-- 用户需要登录时跳转的地址 -->
  119. <bean id="authenticationEntryPoint" class="com.common.security.AuthenticationEntryPoint">
  120. <property name="loginFormUrl" value="/loginre.jsp" />
  121. </bean>
  122.  
  123. <!-- 用户登录失败 -->
  124. <bean id="loginFail" class="com.common.security.LoginFail">
  125. <property name="url" value="login.jsp" />
  126. </bean>
  127.  
  128. <!-- 用户登录成功 -->
  129. <bean id="loginSuccess" class="com.common.security.loginSuccess">
  130. <property name="url" value="ire.htm" />
  131. </bean>
  132.  
  133. <!-- 注销客户端 -->
  134. <bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" />
  135.  
  136. <!-- 注销服务器端 -->
  137. <bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
  138. <constructor-arg value="${cas.server.url}logout?service=${casClientRoot}" />
  139. <constructor-arg>
  140. <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
  141. </constructor-arg>
  142. <property name="filterProcessesUrl" value="/j_spring_cas_security_logout" />
  143. </bean>
  144.  
  145. </beans>

  代理端请求被代理端的请求

  1. public static String httpURLConnectionPOST(String url) {
  2. //1、从SecurityContextHolder获取到当前的Authentication对象,其是一个CasAuthenticationToken
  3. CasAuthenticationToken cat = (CasAuthenticationToken) SecurityContextHolder.getContext()
  4. .getAuthentication();
  5. //2、获取到AttributePrincipal对象
  6. AttributePrincipal principal = cat.getAssertion().getPrincipal();
  7. //3、获取对应的proxy ticket
  8. String proxyTicket = principal.getProxyTicketFor(url);
  9. try {
  10. //4、请求被代理应用时将获取到的proxy ticket以参数ticket进行传递
  11. url += "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8");
  12. URL assessUrl = new URL(url);
  13. // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接)
  14. HttpURLConnection connection = (HttpURLConnection) assessUrl.openConnection();// 此时cnnection只是为一个连接对象,待连接中
  15. // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
  16. connection.setDoOutput(true);
  17. // 设置连接输入流为true
  18. connection.setDoInput(true);
  19. // 设置请求方式为post
  20. connection.setRequestMethod("POST");
  21. // post请求缓存设为false
  22. connection.setUseCaches(false);
  23. // 设置该HttpURLConnection实例是否自动执行重定向
  24. connection.setInstanceFollowRedirects(true);
  25. // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
  26. // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
  27. // ;charset=utf-8 必须要,不然妙兜那边会出现乱码【★★★★★】
  28. connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  29. // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
  30. connection.connect();
  31. // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
  32. DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
  33. // 输出完成后刷新并关闭流
  34. dataout.flush();
  35. dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
  36.  
  37. //System.out.println(connection.getResponseCode());
  38.  
  39. // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
  40. BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
  41. String line;
  42. StringBuilder sb = new StringBuilder(); // 用来存储响应数据
  43.  
  44. // 循环读取流,若不到结尾处
  45. while ((line = bf.readLine()) != null) {
  46. // sb.append(bf.readLine());
  47. sb.append(line).append(System.getProperty("line.separator"));
  48. }
  49. bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
  50. connection.disconnect(); // 销毁连接
  51. return sb.toString();
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. return null;
  56. }

   被代理端的接口

  1. @RequestMapping(value = "/testPost.json")
  2. public void synUser( String xmlPath) throws Exception {
  3. System.out.println(xmlPath);
  4. }

  

public static String httpURLConnectionPOST(String url) {      //1、从SecurityContextHolder获取到当前的Authentication对象,其是一个CasAuthenticationToken        CasAuthenticationToken cat = (CasAuthenticationToken) SecurityContextHolder.getContext()            .getAuthentication();        //2、获取到AttributePrincipal对象        AttributePrincipal principal = cat.getAssertion().getPrincipal();        //3、获取对应的proxy ticket        String proxyTicket = principal.getProxyTicketFor(url);        try {            //4、请求被代理应用时将获取到的proxy ticket以参数ticket进行传递            url += "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8");            URL assessUrl = new URL(url);            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)            HttpURLConnection connection = (HttpURLConnection) assessUrl.openConnection();// 此时cnnection只是为一个连接对象,待连接中            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)            connection.setDoOutput(true);            // 设置连接输入流为true            connection.setDoInput(true);            // 设置请求方式为post             connection.setRequestMethod("POST");            // post请求缓存设为false            connection.setUseCaches(false);            // 设置该HttpURLConnection实例是否自动执行重定向            connection.setInstanceFollowRedirects(true);            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)            // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据            // ;charset=utf-8 必须要,不然妙兜那边会出现乱码【★★★★★】            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)            connection.connect();            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());            // 输出完成后刷新并关闭流            dataout.flush();            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!) 
            //System.out.println(connection.getResponseCode());
            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));            String line;            StringBuilder sb = new StringBuilder(); // 用来存储响应数据
            // 循环读取流,若不到结尾处            while ((line = bf.readLine()) != null) {                //                sb.append(bf.readLine());                sb.append(line).append(System.getProperty("line.separator"));            }            bf.close(); // 重要且易忽略步骤 (关闭流,切记!)             connection.disconnect(); // 销毁连接            return sb.toString();        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

spring security+cas(cas proxy配置)的更多相关文章

  1. Spring Security 集成 CAS(基于HTTP协议版本)

    Spring Security 集成 CAS(基于HTTP协议版本) 近段时间一直研究Spring Security 集成 CAS,网上资料相关资料也很多,不过大都是基于Https的安全认证;使用ht ...

  2. Spring Security 集成CAS实现单点登录

    参考:http://elim.iteye.com/blog/2270446 众所周知,Cas是对单点登录的一种实现.本文假设读者已经了解了Cas的原理及其使用,这些内容在本文将不会讨论.Cas有Ser ...

  3. spring security集成cas实现单点登录

    spring security集成cas 0.配置本地ssl连接 操作记录如下: =====================1.创建证书文件thekeystore ,并导出为thekeystore.c ...

  4. Spring Security 之Session管理配置

    废话不多说,直接上代码.示例如下: 1.   新建Maven项目  session 2.   pom.xml <project xmlns="http://maven.apache.o ...

  5. spring boot rest 接口集成 spring security(1) - 最简配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  6. Spring Security 入门(1-3-2)Spring Security - http元素 - intercept-url配置

    http元素下可以配置登录页面,也可以配置 url 拦截. 1.直接配置拦截url和对应的访问权限 <security:http use-expressions="false" ...

  7. Spring Security OAuth2之resource_id配置与验证

    一.resource_id的作用 Spring Security OAuth2 架构上分为Authorization Server认证服务器和Resource Server资源服务器.我们可以为每一个 ...

  8. SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑

    前言 最近在做项目的时候,基于前后端分离的权限管理系统,后台使用 Spring Security 作为权限控制管理, 然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用 ...

  9. Spring Security(4):自定义配置

    接着上节的讲,在添加了@EnableWebSecurity注解后,如果需要自定义一些配置,则需要和继承WebSecurityConfigurerAdapter后,覆盖某些方法. 我们来看一下WebSe ...

  10. Spring Security (Acegi)的登陆配置

    简短记录一下: 在authenticationProcessingFilter这个bean中,如果没有配置<property name="alwaysUseDefaultTargetU ...

随机推荐

  1. SSH使用主机名访问

    比如说A电脑已经和B电脑实现了ssh免密码登陆!但是A电脑通过 ssh B电脑的主机名称 不行! 解决办法: 01.修改A电脑中的hosts文件    vim /etc/hosts 02.进入编辑界面 ...

  2. L175 Endorestiform Nucleus: Scientist Just Discovered a New Part of the Human Brain

    The newly named Endorestiform Nucleus sits in the inferior cerebellar小脑 peduncle, at the junction be ...

  3. Sqlserver 按照时间段统计数据

    WITH t1 ( [hour], title ) , ' 0:00:00--- 1:00:00' UNION ALL , ' 1:00:00--- 2:00:00' UNION ALL , ' 2: ...

  4. redux中的compose源码分析

    1. redux中compose用来组合各种中间件来实现链式调用,例子如下 compose( applyMiddleware, devTools, persistState, createStore ...

  5. 移动端H5调用摄像头(选择上传图片)

    <label>照相机</label> <input type="file" id='image' accept="image/*" ...

  6. TCP滑动窗口与回退N针协议

    [转]TCP 滑动窗口协议/1比特滑动窗口协议/后退n协议/选择重传协议 2014-1-5阅读884 评论0 本文转自 http://www.cnblogs.com/ulihj/archive/201 ...

  7. Git 学习记录一

    主要来源参考http://www.runoob.com/git/git-install-setup.html Windows 平台上安装 在 Windows 平台上安装 Git 同样轻松,有个叫做 m ...

  8. Linux内核配置---menuconfig

    1. 示例 config SGI_NEWPORT_CONSOLE tristate "SGI Newport Console support" depends on SGI_IP2 ...

  9. visual studio内置“iis”组件提取及二次开发

    简介 visual studio安装后会自带小型的“iis”服务器,本文就简单提取一下这个组件,自己做一个小型“iis”服务器吧.先来说用途吧(废话可绕过),比如在服务器上没有安装iis,或者给客户演 ...

  10. DataTable快速定制之Expression属性表达式

    本文旨在讨论使用DataColumn.Expression属性定制列,高手绕过. 这里只介绍两个经典的场景,抛砖引玉其他更多功能待各位读者自己发现吧! 场景一: DataTable里有两个列分别为每种 ...