spring security+cas(cas proxy配置)

什么时候会用到代理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

<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to Apereo under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Apereo licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License.  You may obtain a
    copy of the License at the following location:

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<!--
| deployerConfigContext.xml centralizes into one file some of the declarative configuration that
| all CAS deployers will need to modify.
|
| This file declares some of the Spring-managed JavaBeans that make up a CAS deployment.
| The beans declared in this file are instantiated at context initialization time by the Spring
| ContextLoaderListener declared in web.xml.  It finds this file because this
| file is among those declared in the context parameter "contextConfigLocation".
|
| By far the most common change you will need to make in this file is to change the last bean
| declaration to replace the default authentication handler with
| one implementing your approach for authenticating usernames and passwords.
+-->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--
       | The authentication manager defines security policy for authentication by specifying at a minimum
       | the authentication handlers that will be used to authenticate credential. While the AuthenticationManager
       | interface supports plugging in another implementation, the default PolicyBasedAuthenticationManager should
       | be sufficient in most cases.
       +-->
    <bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager">
        <constructor-arg>
            <map>
                <!--
                   | IMPORTANT
                   | Every handler requires a unique name.
                   | If more than one instance of the same handler class is configured, you must explicitly
                   | set its name to something other than its default name (typically the simple class name).
                   -->
                <entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />
                <entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />
                 <!-- key-ref指定自己的本地数据库访问 -->
				<entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>
            </map>
        </constructor-arg>

        <!-- Uncomment the metadata populator to capture the password.
        <property name="authenticationMetaDataPopulators">
           <util:list>
               <bean class="org.jasig.cas.authentication.CacheCredentialsMetaDataPopulator"/>
           </util:list>
        </property>
        -->

        <!--
           | Defines the security policy around authentication. Some alternative policies that ship with CAS:
           |
           | * NotPreventedAuthenticationPolicy - all credential must either pass or fail authentication
           | * AllAuthenticationPolicy - all presented credential must be authenticated successfully
           | * RequiredHandlerAuthenticationPolicy - specifies a handler that must authenticate its credential to pass
           -->
        <property name="authenticationPolicy">
            <bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" />
        </property>
    </bean>

    <!-- Required for proxy ticket mechanism. -->
    <bean id="proxyAuthenticationHandler"
          class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
          p:httpClient-ref="supportsTrustStoreSslSocketFactoryHttpClient" p:requireSecure="false"/>

    <!--
       | TODO: Replace this component with one suitable for your enviroment.
       |
       | This component provides authentication for the kind of credential used in your environment. In most cases
       | credential is a username/password pair that lives in a system of record like an LDAP directory.
       | The most common authentication handler beans:
       |
       | * org.jasig.cas.authentication.LdapAuthenticationHandler
       | * org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler
       | * org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler
       | * org.jasig.cas.support.spnego.authentication.handler.support.JCIFSSpnegoAuthenticationHandler
       -->
    <bean id="primaryAuthenticationHandler"
          class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">
        <property name="users">
            <map>
                <entry key="casuser" value="Mellon"/>
            </map>
        </property>
    </bean>

    <!-- Required for proxy ticket mechanism -->
    <bean id="proxyPrincipalResolver"
          class="org.jasig.cas.authentication.principal.BasicPrincipalResolver" />

    <!--
       | Resolves a principal from a credential using an attribute repository that is configured to resolve
       | against a deployer-specific store (e.g. LDAP).
       -->
    <bean id="primaryPrincipalResolver"
          class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver"
          p:principalFactory-ref="principalFactory"
          p:attributeRepository-ref="attributeRepository" />

    <!--
    Bean that defines the attributes that a service may return.  This example uses the Stub/Mock version.  A real implementation
    may go against a database or LDAP server.  The id should remain "attributeRepository" though.
    +-->

    <bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao"> 
	    <constructor-arg index="0" ref="dataSource" /> 
	    <constructor-arg index="1" value="select ID_ as id,PASSWORD_ as pwd from USER_TABLE where {0}" /> 
	    <property name="queryAttributeMapping"> 
	       <map> 
	           <!-- 这里的key需写username和登录页面一致,value对应数据库用户名字段 
	           		select ID_ as id from USER_TABLE where USERNAME_=#username#
	            -->
	           <entry key="username" value="USERNAME_"/> 
	       </map> 
	    </property> 
	    <property name="resultAttributeMapping"> 
	       <map> 
	          <!--  key为对应的数据库字段名称,value为提供给客户端获取的属性名字,系统会自动填充值  -->
	           <entry key="id" value="id"/> 
	           <entry key="pwd" value="pwd"/> 
	       </map> 
	    </property> 
    </bean>


     <bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl" 
      p:registeredServices-ref="registeredServicesList" />
      
      <util:list id="registeredServicesList">
	    <bean class="org.jasig.cas.services.RegexRegisteredService"
	          p:id="1"
	          p:name="HTTPS and IMAPS services on example.com"
	          p:serviceId="^(https?|imaps?|http?)://.*"
	          p:evaluationOrder="0" >
	          <!-- 基于正则表达式匹配代理端,以下这行不加的话代理端会被cas server拒绝 -->
	            <property name="proxyPolicy">
	        		<bean class="org.jasig.cas.services.RegexMatchingRegisteredServiceProxyPolicy" c:pgtUrlPattern="^https?://.*" />
	            </property>
	   </bean>
	</util:list>

    <bean id="auditTrailManager" class="org.jasig.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />

    <bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor" p:monitors-ref="monitorsList" />

    <util:list id="monitorsList">
        <bean class="org.jasig.cas.monitor.MemoryMonitor" p:freeMemoryWarnThreshold="10" />
        <!--
          NOTE
          The following ticket registries support SessionMonitor:
            * DefaultTicketRegistry
            * JpaTicketRegistry
          Remove this monitor if you use an unsupported registry.
        -->
        <bean class="org.jasig.cas.monitor.SessionMonitor"
              p:ticketRegistry-ref="ticketRegistry"
              p:serviceTicketCountWarnThreshold="5000"
              p:sessionCountWarnThreshold="100000" />
    </util:list>
    
    <!-- 访问本地数据库 -->
	<bean id="dbAuthHandler"
	      class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
	      <property name="dataSource" ref="dataSource"></property>  
	      <property name="sql" value="SELECT PASSWORD_ FROM USER_TABLE WHERE USERNAME_ = ? and ISACTIVE_='Y' "></property> 
		  <property name="passwordEncoder" ref="MD5PasswordEncoder"></property>
	</bean>	  
	  
	<!-- SSO密码加密配置 -->  
    <bean id="MD5PasswordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder">  
        <constructor-arg index="0">  
            <value>MD5</value>  
        </constructor-arg>  
    </bean> 
    
    <!-- mysql连接 -->
	<!--  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
	    <property name="url" value="jdbc:mysql://localhost:3306/cas?useUnicode=true&characterEncoding=UTF-8"/>
	    <property name="username" value="root" />
	    <property name="password" value="root" />
	</bean> -->
	
	<!-- oracle连接 -->
	 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
		<property name="username" value="username" />
		<property name="password" value="password" />
	</bean>
</beans>

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:s="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

	<!-- <s:http pattern="/saveMyCss.json" security="none" />  -->
	<!-- sso -->
	<s:http auto-config="true" entry-point-ref="casAuthenticationEntryPoint"  servlet-api-provision="true">
		<s:intercept-url pattern="/login.jsp" access="ROLE_USER"></s:intercept-url>
		<s:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />  
		<s:custom-filter ref="singleLogoutFilter" before="CAS_FILTER" /> 
		<!-- 增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前-->
		<s:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>
		<s:custom-filter ref="casAuthenticationFilter" position="CAS_FILTER" />
	</s:http>
	
	<s:authentication-manager alias="authenticationManager">
		<s:authentication-provider ref="casAuthenticationProvider"></s:authentication-provider>
	</s:authentication-manager>
	
	<!-- http://localhost:8088/SpringSecurity 具体应用 -->
	<!-- j_spring_cas_security_check spring的虚拟URL,此标志标识使用 CAS authentication upon return from CAS SSO login. -->
	<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
		<property name="service" value="${casClientRoot}j_spring_cas_security_check"></property>
		<property name="sendRenew" value="false"></property>
	</bean>
	
	<!-- 配置ProxyGrantingTicketStorage,用以保存pgtId和pgtIou -->
	<bean id="proxyGrantingTicketStorage" class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl"/>
	
	<bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
		<property name="authenticationManager" ref="authenticationManager" />
		<property name="authenticationSuccessHandler" ref="loginSuccess" />
		<property name="authenticationFailureHandler" ref="loginFail" />
		<!-- 指定处理地址,不指定时默认将会是“/j_spring_cas_security_check” -->
		<property name="filterProcessesUrl" value="/j_spring_cas_security_check" />
		<!-- 保存cas server传递过来的pgtId和pgtIou -->
		<property name="proxyGrantingTicketStorage" ref="proxyGrantingTicketStorage"/>
		<!-- 用以指定Cas Server在回调代理端传递pgtId和pgtIou时回调地址相对于代理端的路径 -->
		<property name="proxyReceptorUrl" value="/proxyCallback"/>
	</bean>
	
	<!-- loginUrl cas 服务登录地址 -->
	<bean id="casAuthenticationEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
		<property name="loginUrl" value="${cas.server.url}login" /> 
		<property name="serviceProperties" ref="serviceProperties" />
	</bean>
	
	<!-- ticketValidator cas服务验证地址 -->
	<bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
		<property name="userDetailsService" ref="userDetailServiceImpl" />
		<property name="serviceProperties" ref="serviceProperties" />
		<!-- 配置TicketValidator在登录认证成功后验证ticket -->
		<property name="ticketValidator">
			<bean class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator">
				<!-- Cas Server访问地址的前缀,即根路径-->
				<!-- cas.server.url https://localhost:8888/cas-server/ -->
				<constructor-arg index="0" value="${cas.server.url}" />
				<!-- 指定Cas Server回调传递pgtId和pgtIou的地址,该地址必须使用https协议 -->
				<!-- casClientRoot https://localhost:8080/app1/ -->
				<property name="proxyCallbackUrl" value="${casClientRoot}proxyCallback"/>
				<property name="proxyGrantingTicketStorage" ref="proxyGrantingTicketStorage"/>
			</bean>
		</property>
		<property name="key" value="key4CasAuthenticationProvider" />
	</bean>
	
	<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"></bean>
	
	<!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性,
		我们的所有控制将在这三个类中实现,解释详见具体配置 -->
	<bean id="filterSecurityInterceptor"
		class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
		<property name="authenticationManager" ref="authenticationManager" />
		<property name="accessDecisionManager" ref="dbAccessDecisionManagerBean" />
		<property name="securityMetadataSource" ref="securityMetadataSource" />
	</bean>
	
	<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
	
	<bean id="userDetailServiceImpl" class="com.common.security.UserDetailsServiceImpl">
		<property name="dao" ref="dao" />
	</bean>
	
	<!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
	<bean id="dbAccessDecisionManagerBean" class="com.common.security.DbAccessDecisionManager">
	</bean>

	<!-- 资源源数据定义,即定义某一资源可以被哪些角色访问 -->
	<bean id="securityMetadataSource" class="com.common.security.DbInvocationSecurityMetadataSource">
		<property name="securityData" ref="securityData" />
	</bean>

	<bean id="securityData" class="com.common.security.SecurityData">
		<property name="dao" ref="dao" />
	</bean>
	<!-- 用户需要登录时跳转的地址 -->
	<bean id="authenticationEntryPoint" class="com.common.security.AuthenticationEntryPoint">
		<property name="loginFormUrl" value="/loginre.jsp" />
	</bean>
	
	<!-- 用户登录失败 -->
	<bean id="loginFail" class="com.common.security.LoginFail">
		<property name="url" value="login.jsp" />
	</bean>

	<!-- 用户登录成功 -->
	<bean id="loginSuccess" class="com.common.security.loginSuccess">
		<property name="url" value="ire.htm" />
	</bean>
	
	 <!-- 注销客户端 --> 
    <bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" /> 
	
	<!-- 注销服务器端 --> 
    <bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"> 
	    <constructor-arg  value="${cas.server.url}logout?service=${casClientRoot}" /> 
	    <constructor-arg> 
	    	<bean  class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/> 
	    </constructor-arg> 
	    <property name="filterProcessesUrl" value="/j_spring_cas_security_logout" /> 
    </bean> 

</beans>

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:s="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

	<!-- <s:http pattern="/saveMyCss.json" security="none" />  -->
	<!-- sso -->
	<s:http auto-config="true" entry-point-ref="casAuthenticationEntryPoint"  servlet-api-provision="true">
		<s:intercept-url pattern="/login.jsp" access="ROLE_USER"></s:intercept-url>
		<s:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />  
		<s:custom-filter ref="singleLogoutFilter" before="CAS_FILTER" /> 
		<!-- 增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前-->
		<s:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>
		<s:custom-filter ref="casAuthenticationFilter" position="CAS_FILTER" />
	</s:http>
	
	<s:authentication-manager alias="authenticationManager">
		<s:authentication-provider ref="casAuthenticationProvider"></s:authentication-provider>
	</s:authentication-manager>
	
	<!-- http://localhost:8088/SpringSecurity 具体应用 -->
	<!-- j_spring_cas_security_check spring的虚拟URL,此标志标识使用 CAS authentication upon return from CAS SSO login. -->
	<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
		<!-- casClientRoot https://localhost:8080/app2/ -->
		<property name="service" value="${casClientRoot}j_spring_cas_security_check"></property>
		<!-- <property name="sendRenew" value="false" /> -->
		<!-- 通过ServiceProperties指定CasAuthenticationFilter的authenticateAllArtifacts为true -->
		<property name="authenticateAllArtifacts" value="true"/>
	</bean>
	
	<bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
		<property name="authenticationManager" ref="authenticationManager" />
		<property name="authenticationSuccessHandler" ref="loginSuccess" />
		<property name="authenticationFailureHandler" ref="loginFail" />
		<!-- 指定处理地址,不指定时默认将会是“/j_spring_cas_security_check” -->
		<property name="filterProcessesUrl" value="/j_spring_cas_security_check" />
		<!-- 通过ServiceProperties指定CasAuthenticationFilter的authenticateAllArtifacts为true  -->
		<property name="serviceProperties" ref="serviceProperties" />
		<!-- 指定使用的AuthenticationDetailsSource为ServiceAuthenticationDetailsSource -->
		<property name="authenticationDetailsSource">
			<bean class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource" />
		</property>
	</bean>
	
	<!-- loginUrl cas 服务登录地址 -->
	<bean id="casAuthenticationEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
		<property name="loginUrl" value="${cas.server.url}login" /> 
		<property name="serviceProperties" ref="serviceProperties" />
	</bean>
	
	<!-- ticketValidator cas服务验证地址 -->
	<bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
		<property name="userDetailsService" ref="userDetailServiceImpl" />
		<property name="serviceProperties" ref="serviceProperties" />
		<!-- 配置TicketValidator在登录认证成功后验证ticket -->
		<property name="ticketValidator">
			<bean class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator">
				<!-- Cas Server访问地址的前缀,即根路径-->
				<!-- cas.server.url https://localhost:8888/cas-server/ -->
				<constructor-arg index="0" value="${cas.server.url}" />
				<!-- 如果有多个代理端可以多写几个value -->
				<property name="allowedProxyChains">
					<value>https://localhost:8080/app1/proxyCallback</value>
				</property>
			</bean>
		</property>
		<property name="key" value="key4CasAuthenticationProvider" />
		<property name="statelessTicketCache">
			<bean class="org.springframework.security.cas.authentication.EhCacheBasedTicketCache">
				<!-- Ehcache对象 -->
				<property name="cache" ref="proxyTicketCache"/>
			</bean>
		</property>
	</bean>
	
	<!-- 定义一个Ehcache -->
   <bean id="proxyTicketCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
      <property name="cacheName" value="proxyTicketCache" />
      <property name="timeToLive" value="600"/>
   </bean>
	
	<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"></bean>
	
	<!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性,
		我们的所有控制将在这三个类中实现,解释详见具体配置 -->
	<bean id="filterSecurityInterceptor"
		class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
		<property name="authenticationManager"
			ref="authenticationManager" />
		<property name="accessDecisionManager"
			ref="dbAccessDecisionManagerBean" />
		<property name="securityMetadataSource"
			ref="securityMetadataSource" />
	</bean>
	
	<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
	
	<bean id="userDetailServiceImpl" class="com.common.security.UserDetailsServiceImpl">
		<property name="dao" ref="dao" />
	</bean>
	
	<!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
	<bean id="dbAccessDecisionManagerBean" class="com.common.security.DbAccessDecisionManager">
	</bean>

	<!-- 资源源数据定义,即定义某一资源可以被哪些角色访问 -->
	<bean id="securityMetadataSource" class="com.common.security.DbInvocationSecurityMetadataSource">
		<property name="securityData" ref="securityData" />
	</bean>

	<bean id="securityData" class="com.common.security.SecurityData">
		<property name="dao" ref="dao" />
	</bean>
	<!-- 用户需要登录时跳转的地址 -->
	<bean id="authenticationEntryPoint" class="com.common.security.AuthenticationEntryPoint">
		<property name="loginFormUrl" value="/loginre.jsp" />
	</bean>
	
	<!-- 用户登录失败 -->
	<bean id="loginFail" class="com.common.security.LoginFail">
		<property name="url" value="login.jsp" />
	</bean>

	<!-- 用户登录成功 -->
	<bean id="loginSuccess" class="com.common.security.loginSuccess">
		<property name="url" value="ire.htm" />
	</bean>
	
	 <!-- 注销客户端 --> 
    <bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" /> 
	
	<!-- 注销服务器端 --> 
    <bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"> 
	    <constructor-arg  value="${cas.server.url}logout?service=${casClientRoot}" /> 
	    <constructor-arg> 
	    	<bean  class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/> 
	    </constructor-arg> 
	    <property name="filterProcessesUrl" value="/j_spring_cas_security_logout" /> 
    </bean> 

</beans>

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

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;
    }

   被代理端的接口

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

  

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;    }

转载于:https://www.cnblogs.com/l412382979/p/9120837.html

cas 配置client 1.0 &2.0 及proxy DEMO 说明 1 cas server 搭建 1.1 资源准备 cas server 下载 http://www.ja-sig.org/downloads/cas/cas-server-3.3.1-release.zip 1.2 解压后打开cas-server-3.3.1-release\cas-server-3.3.1\modules ,将cas-server-webapp-3.3.1.war 重命名为cas.war,并将war包拷贝到tomcat5.5以上版本的webapps目录下(在此对server jdbc支持不做详细解读,测试使用CAS simaple提供的默认用户名 密码 cas/cas) 2 证书生成及导入 2.1 Server端证书配置 2.2 2.2.1 证书生成导入 2.2.1.1 keytool -delete -alias tomcatsso -keystore cacerts -storepass changeit 2.2.1.2 keytool -list -keystore cacerts -storepass changeit 2.2.1.3 keytool -genkey -keyalg RSA -alias tomcatsso -dname "cn=www.test.com" -keystore cacerts -storepass changeit 2.2.1.4 keytool -export -alias tomcatsso -file tomcatsso.crt -keystore cacerts -storepass changeit 2.2.1.5 keytool -import -alias tomcatsso -file tomcatsso.crt -keystore cacerts -storepass changeit 2.2.1.6 keytool -list -keystore cacerts -storepass changeit 说明:在生成key的过程,"cn=www.test.com" 中的www.test.com为Server端的域名(必填)。 2.2.2 TOMCAT 配置SSL支持 2.2.2.1 将cacerts文件复制到TOMCAT的conf目录下修改server.xml <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="443" /> <Connector port="443" minSpareThreads="5" maxSpareThreads="75" enableLookups="true" disableUploadTimeout="true" acceptCount="100" maxThreads="200" scheme="https" secure="true" SSLEnabled="true" clientAuth="false" sslProtocol="TLS" keystoreFile="conf/cacerts" keystorePass="changeit" truststoreFile="conf/cacerts"/> 启动Tomcat,测试https://www.test.com:443 2.2.3 客户端证书导入 2.2.3.1 .\jre\lib\security>keytool -import -alias tomcatsso -file tomcatsso.crt -keystore cacerts -storepass changeit 3 cas client 1.0配置说明 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <description>cas1 demo</description> <!-- cas filter --> <filter> <filter-name>CAS Filter</filter-name> <filter-class> edu.yale.its.tp.cas.client.filter.CASFilter </filter-class> <!-- server login url --> <init-param> <param-name> edu.yale.its.tp.cas.client.filter.loginUrl </param-name> <param-value> https://www.test.com:8443/cas/login </param-value> </init-param> <!-- server validate url --> <init-param> <param-name> edu.yale.its.tp.cas.client.filter.validateUrl </param-name> <param-value> https://www.test.com:8443/cas/proxyValidate </param-value> </init-param> <!-- local web url --> <init-param> <param-name> edu.yale.its.tp.cas.client.filter.serverName </param-name> <param-value>www.teste.com:8080</param-value> </init-param> </filter> <!-- CAS Filter mapping --> <filter-mapping> <filter-name>CAS Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> 4 cas client 2.0配置说明 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <description>cas client test</description> <!--CAS Authentication FILTER --> <filter> <filter-name>CAS Authentication Filter</filter-name> <filter-class> org.jasig.cas.client.authentication.AuthenticationFilter </filter-class> <!-- cas server LOGIN URL --> <!-- https://www.test.com:8443/cas/login--> <init-param> <param-name>casServerLoginUrl</param-name> <param-value> https://www.test.com:8443/cas/login </param-value> </init-param> <!-- local web URL --> <init-param> <param-name>serverName</param-name> <param-value>http://www.testd.com:8080</param-value> </init-param> </filter> <!-- CAS Validation FILTER --> <filter> <filter-name>CAS Validation Filter</filter-name> <filter-class> org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter </filter-class> <!-- CAS SERVER URL --> <!-- https://www.test.com:8443/cas --> <init-param> <param-name>casServerUrlPrefix</param-name> <param-value>https://www.test.com:8443/cas</param-value> </init-param> <!-- LOCAL web URL --> <init-param> <param-name>serverName</param-name> <param-value>http://www.testd.com:8080</param-value> </init-param> <!-- if validation false throw exception ; default true--> <init-param> <param-name>exceptionOnValidationFailure</param-name> <param-value>false</param-value> </init-param> </filter> <!-- cas security username on request.getRemoteUser() --> <filter> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <filter-class> org.jasig.cas.client.util.HttpServletRequestWrapperFilter </filter-class> </filter> <!-- CAS SINGLE SIGN OUT FILTER --> <filter> <filter-name>CAS Single Sign Out Filter</filter-name> <filter-class> org.jasig.cas.client.session.SingleSignOutFilter </filter-class> </filter> <filter-mapping> <filter-name>CAS Single Sign Out Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS Validation Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS Authentication Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping> <!-- SingleSignOutHttpSessionListener LISTENER --> <listener> <listener-class> org.jasig.cas.client.session.SingleSignOutHttpSessionListener </listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> 5 cas client 2.0 proxy 配置说明 proxy web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <description>cas client test</description> <!--CAS Authentication FILTER --> <filter> <filter-name>CAS Authentication Filter</filter-name> <filter-class> org.jasig.cas.client.authentication.AuthenticationFilter </filter-class> <!-- cas server LOGIN URL --> <!-- http://www.test.com:8880 --> <init-param> <param-name>casServerLoginUrl</param-name> <param-value> https://www.test.com:8443/cas/login </param-value> </init-param> <!-- local web URL --> <init-param> <param-name>serverName</param-name> <param-value>http://www.teste.com:8080</param-value> </init-param> </filter> <!-- CAS Validation FILTER --> <filter> <filter-name>CAS Validation Filter</filter-name> <filter-class> org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter </filter-class> <!-- CAS SERVER URL --> <!-- http://www.test.com:8880 --> <init-param> <param-name>casServerUrlPrefix</param-name> <param-value>https://www.test.com:8443/cas</param-value> </init-param> <!-- LOCAL web URL --> <init-param> <param-name>serverName</param-name> <param-value>http://www.teste.com:8080</param-value> </init-param> <!-- if validation false throw exception ; default true--> <init-param> <param-name>exceptionOnValidationFailure</param-name> <param-value>false</param-value> </init-param> <!-- the URL to watch for PGTIOU/PGT responses from the CAS server --> <init-param> <param-name>allowedProxyChains</param-name> <param-value>http://www.testd.com:8080/testd</param-value> </init-param> </filter> <!-- cas security username on request.getRemoteUser() --> <filter> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <filter-class> org.jasig.cas.client.util.HttpServletRequestWrapperFilter </filter-class> </filter> <!-- CAS SINGLE SIGN OUT FILTER --> <filter> <filter-name>CAS Single Sign Out Filter</filter-name> <filter-class> org.jasig.cas.client.session.SingleSignOutFilter </filter-class> </filter> <filter-mapping> <filter-name>CAS Single Sign Out Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS Authentication Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS Validation Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping> <!-- SingleSignOutHttpSessionListener LISTENER --> <listener> <listener-class> org.jasig.cas.client.session.SingleSignOutHttpSessionListener </listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> non proxy web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <description>cas client test</description> <!--CAS Authentication FILTER --> <filter> <filter-name>CAS Authentication Filter</filter-name> <filter-class> org.jasig.cas.client.authentication.AuthenticationFilter </filter-class> <!-- cas server LOGIN URL --> <!-- https://www.test.com:8443/cas/login--> <init-param> <param-name>casServerLoginUrl</param-name> <param-value> https://www.test.com:8443/cas/login </param-value> </init-param> <!-- local web URL --> <init-param> <param-name>serverName</param-name> <param-value>http://www.testd.com:8080</param-value> </init-param> </filter> <!-- CAS Validation FILTER --> <filter> <filter-name>CAS Validation Filter</filter-name> <filter-class> org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter </filter-class> <!-- CAS SERVER URL --> <!-- https://www.test.com:8443/cas --> <init-param> <param-name>casServerUrlPrefix</param-name> <param-value>https://www.test.com:8443/cas</param-value> </init-param> <!-- LOCAL web URL --> <init-param> <param-name>serverName</param-name> <param-value>http://www.testd.com:8080</param-value> </init-param> <!-- if validation false throw exception ; default true--> <init-param> <param-name>exceptionOnValidationFailure</param-name> <param-value>false</param-value> </init-param> <!-- validation callback validate url --> <init-param> <param-name>proxyCallbackUrl</param-name> <param-value>http://www.teste.com:8080/teste</param-value> </init-param> <!-- proxyreceptor url --> <init-param> <param-name>proxyReceptorUrl</param-name> <param-value>/proxy/test.jsp</param-value> </init-param> </filter> <!-- cas security username on request.getRemoteUser() --> <filter> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <filter-class> org.jasig.cas.client.util.HttpServletRequestWrapperFilter </filter-class> </filter> <!-- CAS SINGLE SIGN OUT FILTER --> <filter> <filter-name>CAS Single Sign Out Filter</filter-name> <filter-class> org.jasig.cas.client.session.SingleSignOutFilter </filter-class> </filter> <filter-mapping> <filter-name>CAS Single Sign Out Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS Validation Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS Authentication Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping> <!-- SingleSignOutHttpSessionListener LISTENER --> <listener> <listener-class> org.jasig.cas.client.session.SingleSignOutHttpSessionListener </listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> 6 demo 部署及说明 拷贝demo目录下的文件到 相应的发布目录(tomcat/webapps)下,使用解压工具解压,打开对应demo的web.xml,将www.test.com 及 www.testd.com 、www.teste.com 修改为相应的路径 启动TOMCAT ,祝贺你CAS 部署成功了! 7 Cas 非HTTPS支持(不赞成使用) cas client 部分修改 打开edu.yale.its.tp.cas.client.filter类,注释此 if (!pv.isAuthenticationSuccesful()) // throw new ServletException( // "CAS authentication error: " + pv.getErrorCode() + ": " + pv.getErrorMessage()); Cas server 部分修改 打开 cas-server-webapp-3.3.1\WebRoot\WEB-INF\spring-configuration\ticketGrantingTicketCookieGenerator.xml 文件 将 p:cookieSecure="true" 值改为 p:cookieSecure="false" 备注:此文仅供参考,作者仅希望通过此文引导新手,相互交流,若有疑问或意见请与作者联系! 利剑 2008-12-16 QQ:349566018 E-mail:mygw@163.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值