单点登录CAS与Spring Security集成(数据库验证,向客户端发送更多信息)

准备工作

CAS server从网上直接下载下来,里面有一个cas-server-webapp的工程,使用Maven命令构建,导入到Eclipse中,便可以直接使用,cas server我使用的是3.5.2版本。客户端,我是使用以前的工程,只要是Web工程就行,cas-client使用的3.2.1,Spring Security使用的是3.1.4,记得Spring Security的3.1.2版本和CAS集成时,当需要CAS Server传比较多的信息给客户端时,客户端的Spring Security会解析出错(如果木有记错的话)

**PS:**无使用HTTPS协议,需要对CAS Server的配置做改动,具体后面详述

服务端(CAS Server)

服务端部署在8080端口

使用HTTP协议

CAS Server完全使用的是CAS官方的工程,名为cas-server-webapp,导入到Eclipse中之后,就是一普通的Web工程,官方的Demo是需要HTTPS的,此篇讨论的就是普通的HTTP,首先修改ticketGrantingTicketCookieGenerator.xml和warnCookieGenerator.xml这两个文件,将p:cookieSecure属性值设置为false

使用数据库的验证方式登录

使用数据库的验证方式登录,需要修改几个地方,一是配置文件,二是编写自己的数据库查询的类(这个类在3.5.2中提供了,可以通过配置文件实现),也可以自己实现该类。

配置文件

需要修改deployerConfigContext.xml,使用我们自己定义的类验证,配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--
	| 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 SimpleTestUsernamePasswordAuthenticationHandler 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:tx="http://www.springframework.org/schema/tx"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
	<!--
		| This bean declares our AuthenticationManager.  The CentralAuthenticationService service bean
		| declared in applicationContext.xml picks up this AuthenticationManager by reference to its id, 
		| "authenticationManager".  Most deployers will be able to use the default AuthenticationManager
		| implementation and so do not need to change the class of this bean.  We include the whole
		| AuthenticationManager here in the userConfigContext.xml so that you can see the things you will
		| need to change in context.
		+-->
	<bean id="authenticationManager"
		class="org.jasig.cas.authentication.AuthenticationManagerImpl">
		
		<!-- Uncomment the metadata populator to allow clearpass to capture and cache the password
		     This switch effectively will turn on clearpass.
		<property name="authenticationMetaDataPopulators">
		   <list>
		      <bean class="org.jasig.cas.extension.clearpass.CacheCredentialsMetaDataPopulator">
		         <constructor-arg index="0" ref="credentialsCache" />
		      </bean>
		   </list>
		</property>
		 -->
		
		<!--
			| This is the List of CredentialToPrincipalResolvers that identify what Principal is trying to authenticate.
			| The AuthenticationManagerImpl considers them in order, finding a CredentialToPrincipalResolver which 
			| supports the presented credentials.
			|
			| AuthenticationManagerImpl uses these resolvers for two purposes.  First, it uses them to identify the Principal
			| attempting to authenticate to CAS /login .  In the default configuration, it is the DefaultCredentialsToPrincipalResolver
			| that fills this role.  If you are using some other kind of credentials than UsernamePasswordCredentials, you will need to replace
			| DefaultCredentialsToPrincipalResolver with a CredentialsToPrincipalResolver that supports the credentials you are
			| using.
			|
			| Second, AuthenticationManagerImpl uses these resolvers to identify a service requesting a proxy granting ticket. 
			| In the default configuration, it is the HttpBasedServiceCredentialsToPrincipalResolver that serves this purpose. 
			| You will need to change this list if you are identifying services by something more or other than their callback URL.
			+-->
		<property name="credentialsToPrincipalResolvers">
			<list>
				<!--
					| UsernamePasswordCredentialsToPrincipalResolver supports the UsernamePasswordCredentials that we use for /login 
					| by default and produces SimplePrincipal instances conveying the username from the credentials.
					| 
					| If you've changed your LoginFormAction to use credentials other than UsernamePasswordCredentials then you will also
					| need to change this bean declaration (or add additional declarations) to declare a CredentialsToPrincipalResolver that supports the
					| Credentials you are using.
					+-->
<!-- 				<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver" > -->
<!-- 					<property name="attributeRepository" ref="attributeRepository" /> -->
<!-- 				</bean> -->
					<!-- 此处修改了CredentialToPrincipal,因为除了要传递用户信息之处,还要传递一部分权限信息
						若无此需求,可使用UsernamePasswordCredentialsToPrincipalResolver(系统默认)
					 -->
					<bean class="com.wds.security.cas.BaseUsernamePasswordCredentialsToPrincipalResolver"
						p:jdbcTemplate-ref="jdbcTemplate"
					></bean>
				<!--
					| HttpBasedServiceCredentialsToPrincipalResolver supports HttpBasedCredentials.  It supports the CAS 2.0 approach of
					| authenticating services by SSL callback, extracting the callback URL from the Credentials and representing it as a
					| SimpleService identified by that callback URL.
					|
					| If you are representing services by something more or other than an HTTPS URL whereat they are able to
					| receive a proxy callback, you will need to change this bean declaration (or add additional declarations).
					+-->
				<bean
					class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />
			</list>
		</property>

		<!--
			| Whereas CredentialsToPrincipalResolvers identify who it is some Credentials might authenticate, 
			| AuthenticationHandlers actually authenticate credentials.  Here we declare the AuthenticationHandlers that
			| authenticate the Principals that the CredentialsToPrincipalResolvers identified.  CAS will try these handlers in turn
			| until it finds one that both supports the Credentials presented and succeeds in authenticating.
			+-->
		<property name="authenticationHandlers">
			<list>
				<!--
					| This is the authentication handler that authenticates services by means of callback via SSL, thereby validating
					| a server side SSL certificate.
					+-->
				<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
					p:httpClient-ref="httpClient"
					p:requireSecure="true" 
					/>
				<!--
					| This is the authentication handler declaration that every CAS deployer will need to change before deploying CAS 
					| into production.  The default SimpleTestUsernamePasswordAuthenticationHandler authenticates UsernamePasswordCredentials
					| where the username equals the password.  You will need to replace this with an AuthenticationHandler that implements your
					| local authentication strategy.  You might accomplish this by coding a new such handler and declaring
					| edu.someschool.its.cas.MySpecialHandler here, or you might use one of the handlers provided in the adaptors modules.
					+-->
<!-- 				<bean  -->
<!-- 					class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler"> -->
<!-- 					</bean> -->
				<!-- 使用我们自己的验证方式 -->
				<bean class="com.wds.security.cas.UsernamePasswordJDBCAuthenticationHandler"
					p:jdbcTemplate-ref="jdbcTemplate"
					p:passEncoder-ref="passwordEncoder"
					p:saltSource-ref="saltSource"
				>
				</bean>
			</list>
		</property>
	</bean>
	
	<bean id="passwordEncoder"
		class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
	</bean>
	
	<bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
		<property name="userPropertyToUse" value="userCode" />
	</bean>

	<!--
	This bean defines the security roles for the Services Management application.  Simple deployments can use the in-memory version.
	More robust deployments will want to use another option, such as the Jdbc version.
	
	The name of this should remain "userDetailsService" in order for Spring Security to find it.
	 -->
    <!-- <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" />-->

    <sec:user-service id="userDetailsService">
        <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" />
    </sec:user-service>
	
	<!-- 
	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.StubPersonAttributeDao">
		<property name="backingMap">
			<map>
				<entry key="uid" value="uid" />
				<entry key="eduPersonAffiliation" value="eduPersonAffiliation" /> 
				<entry key="groupMembership" value="groupMembership" />
			</map>
		</property>
	</bean>
	
	<!-- 
	Sample, in-memory data store for the ServiceRegistry. A real implementation
	would probably want to replace this with the JPA-backed ServiceRegistry DAO
	The name of this bean should remain "serviceRegistryDao".
	 -->
	<bean
		id="serviceRegistryDao"
        class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
<!--         	<property name="registeredServices"> -->
<!--         		<bean class="org.jasig.cas.services.RegexRegisteredService"> -->
<!--         			<property name="ignoreAttributes" value="false"></property> -->
<!--         		</bean> -->
<!--         	</property> -->
        	
<!--             <property name="registeredServices"> -->
<!--                 <list> -->
<!--                     <bean class="org.jasig.cas.services.RegexRegisteredService"> -->
<!--                         <property name="id" value="0" /> -->
<!--                         <property name="name" value="HTTP and IMAP" /> -->
<!--                         <property name="description" value="Allows HTTP(S) and IMAP(S) protocols" /> -->
<!--                         <property name="serviceId" value="^(https?|imaps?)://.*" /> -->
<!--                         <property name="evaluationOrder" value="10000001" /> -->
<!--                     </bean> -->
                    <!--
                    Use the following definition instead of the above to further restrict access
                    to services within your domain (including subdomains).
                    Note that example.com must be replaced with the domain you wish to permit.
                    -->
                    <!--
                    <bean class="org.jasig.cas.services.RegexRegisteredService">
                        <property name="id" value="1" />
                        <property name="name" value="HTTP and IMAP on example.com" />
                        <property name="description" value="Allows HTTP(S) and IMAP(S) protocols on example.com" />
                        <property name="serviceId" value="^(https?|imaps?)://([A-Za-z0-9_-]+\.)*example\.com/.*" />
                        <property name="evaluationOrder" value="0" />
                    </bean>
                    -->
<!--                 </list> -->
<!--             </property> -->
        </bean>

  <bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />
  
  <bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor">
    <property name="monitors">
      <list>
        <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" />
      </list>
    </property>
  </bean>
</beans>

数据库访问类

该类根据输入的用户名,去查询数据,并对密码进行验证

package com.wds.security.cas;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import com.wds.security.pojo.BaseUser;
import com.wds.security.pojo.BaseUserDetail;

public class UsernamePasswordJDBCAuthenticationHandler extends
		AbstractUsernamePasswordAuthenticationHandler {

	private JdbcTemplate jdbcTemplate;
	
	private PasswordEncoder passEncoder;
	
	private SaltSource saltSource;
	
	@Override
	protected boolean authenticateUsernamePasswordInternal(
			UsernamePasswordCredentials credentials)
			throws AuthenticationException {
		final String username = credentials.getUsername();
		final String password = credentials.getPassword();
		
		String sql = " select * from  base_user where status = 1 and user_account ='" + username + "'";
		BaseUser baseUser = jdbcTemplate.queryForObject(sql, null, new RowMapper<BaseUser>(){
			@Override
			public BaseUser mapRow(ResultSet rs, int rowNum)
					throws SQLException {
				BaseUser baseuser = new BaseUser();
				baseuser.setCode(rs.getString("code"));
				baseuser.setUserAccount(rs.getString("user_account"));
				baseuser.setUserPassword(rs.getString("user_password"));
				baseuser.setUserName(rs.getString("user_name"));
				return baseuser;
			}
			
		});
		
		List<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
		GrantedAuthority ga = new SimpleGrantedAuthority("admin");
		auth.add(ga);
		
		BaseUserDetail user = new BaseUserDetail(username, baseUser.getUserName(), baseUser.getUserPassword(),  baseUser.getCode(), true, true, true, true, auth);
		
		if(user != null){
			//验证密码
			String encodePassword = this.passEncoder.encodePassword(password, this.saltSource.getSalt(user));
			if(encodePassword.equals(user.getPassword())){
				return true;
			}
		}
		return false;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public void setPassEncoder(PasswordEncoder passEncoder) {
		this.passEncoder = passEncoder;
	}

	public void setSaltSource(SaltSource saltSource) {
		this.saltSource = saltSource;
	}

}
另外还有一个加密使用的类如下:

package com.wds.security.cas;

import org.jasig.cas.authentication.handler.PasswordEncoder;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;

public class MD5PassworEncoder extends MessageDigestPasswordEncoder implements
		PasswordEncoder {

	private SaltSource saltSource;

	private UserDetails user;

	public MD5PassworEncoder(String algorithm) {
		super("MD5");
	}

	@Override
	public String encode(String password) {
		return encodePassword(password, this.saltSource.getSalt(user));
	}

	public void setSaltSource(SaltSource saltSource) {
		this.saltSource = saltSource;
	}

	public void setUser(UserDetails user) {
		this.user = user;
	}

}
当然,还有一些数据库的配置,文中不再列出了

传送更多的信息

在做单点时,如果是默认配置,只能传输用户名到客户端,现希望可以传送更多的信息给客户端,例如,用户拥有的权限信息,可以传给客户,基于以上的配置,需要增加一个类,代码如下:
package com.wds.security.cas;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

public class BaseUsernamePasswordCredentialsToPrincipalResolver implements
		CredentialsToPrincipalResolver {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseUsernamePasswordCredentialsToPrincipalResolver.class);
	
	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public Principal resolvePrincipal(Credentials credentials) {
		UsernamePasswordCredentials up = (UsernamePasswordCredentials) credentials;

		// 获取登录帐户
		logger.debug("登录用户:" + up.getUsername());
//		System.out.println(up.getPassword());
		final Map<String, Object> attr = new HashMap<String, Object>();

		String sql = "select resource_url from v_user_role_resources where user_account ='" + up.getUsername() + "'";
		
		List<String> list = jdbcTemplate.queryForList(sql, String.class);
		attr.put(up.getUsername(), list);
		
		Principal p = new SimplePrincipal(up.getUsername(), attr);
		return p;
	}

	@Override
	public boolean supports(Credentials credentials) {
		return credentials != null
				&& UsernamePasswordCredentials.class
						.isAssignableFrom(credentials.getClass());
	}

}
此外,还需要修改验证成功的JSP界面casServiceValidationSuccess.jsp,代码如下:
<%--

    Licensed to Jasig under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Jasig 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.

--%>
<%@ page session="false" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
	<cas:authenticationSuccess>
		<cas:user>${fn:escapeXml(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.id)}</cas:user>
		<c:if test="${not empty pgtIou}">
			<cas:proxyGrantingTicket>${pgtIou}</cas:proxyGrantingTicket>
		</c:if>
		<c:if test="${fn:length(assertion.chainedAuthentications) > 1}">
			<cas:proxies>
				<c:forEach var="proxy" items="${assertion.chainedAuthentications}"
					varStatus="loopStatus" begin="0"
					end="${fn:length(assertion.chainedAuthentications)-2}" step="1">
					<cas:proxy>${fn:escapeXml(proxy.principal.id)}</cas:proxy>
				</c:forEach>
			</cas:proxies>
		</c:if>
		
		<c:if
			test="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes) > 0}">
			<cas:attributes>
				<c:forEach var="attr"
					items="${assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes}">
					<c:choose>
						<c:when test="${fn:length(attr.value) > 0}">
							<c:forEach var="v" items="${attr.value}">
								<cas:${fn:escapeXml(attr.key)}>${fn:escapeXml(v)}</cas:${fn:escapeXml(attr.key)}>
							</c:forEach>
						</c:when>
						<c:otherwise>
							<cas: ${fn:escapeXml(attr.key)}>${fn:escapeXml(attr.value)}</cas:${fn:escapeXml(attr.key)}>
						</c:otherwise>
					</c:choose>
				</c:forEach>
			</cas:attributes>
		</c:if>
	</cas:authenticationSuccess>
</cas:serviceResponse>
至此,服务端配置完成,

客户端

客户端部署在8083端口,只有一个Spring-Security的配置文件,文件内容如下:

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

	<beans:description>SpringSecurity</beans:description>

	<beans:bean id="customWebInvocationPrivilegeEvaluator"
		class="org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator">
		<beans:constructor-arg ref="baseFilter" />
	</beans:bean>

	<http pattern="/mainfream/index.jsp" security="none" />
	<http pattern="/index.jsp" security="none" />
	<http pattern="/**/*.css" security="none" />
	<http pattern="/**/*.ico" security="none" />
	<http pattern="/**/*.js" security="none" />
	<http pattern="/**/*.jpg" security="none" />
	<http pattern="/**/*.png" security="none" />
	<http pattern="/**/*.gif" security="none" />
	<http pattern="/**/*.pdf" security="none" />
	<http pattern="/**/*.xls" security="none" />
	<http pattern="/**/*.xml" security="none" />
	<http pattern="/upload/**" security="none" />

	<!-- http安全配置 -->
	<http auto-config="true" entry-point-ref="casEntryPoint"
		use-expressions="true" servlet-api-provision="true">
		<intercept-url pattern="/**/*" access="isAuthenticated()" />

		<!-- 尝试访问没有权限的页面时跳转的页面 -->
		<access-denied-handler error-page="/404.jsp" />

		<!-- authentication-success-handler-ref 成功之后处理类 -->
		<form-login login-page="/mainfream/index_index.jsp"
			default-target-url="/mainfream/index_index.jsp"
			authentication-failure-url="https://wds:8443/cas-server-webapp"
			authentication-success-handler-ref="baseSuccessHandler" />
		<logout invalidate-session="true" logout-success-url="https://wds:8443/cas-server-webapp" />
		<session-management session-fixation-protection="none">
			<concurrency-control />
		</session-management>
		<!-- 增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前 -->
		<custom-filter ref="casFilter" position="CAS_FILTER" />
		<custom-filter ref="baseFilter" before="FILTER_SECURITY_INTERCEPTOR" />
		<!-- <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" 
			/> -->
		<custom-filter ref="singleLogoutFilter" before="CAS_FILTER" />
		<!-- <custom-filter ref="mySuccessHandlerFilter" after="FORM_LOGIN_FILTER" 
			/> -->
	</http>

	<!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性, 
		我们的所有控制将在这三个类中实现,解释详见具体配置 -->
	<beans:bean id="baseFilter"
		class="com.gv.base.security.BaseFilterSecurityInterceptor">
		<beans:property name="authenticationManager" ref="authenticationManager" />
		<beans:property name="accessDecisionManager" ref="accessDecisionManagerBean" />
		<beans:property name="securityMetadataSource" ref="securityMetadataSource" />
	</beans:bean>

	<!-- 用户的密码加密或解密 -->
	<beans:bean id="passwordEncoder"
		class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
	</beans:bean>

	<!-- 项目实现的用户查询服务,将用户信息查询出来 -->
	<beans:bean id="userDetailsService"
		class="com.gv.base.security.BaseUserDetailsServiceImpl" />

	<!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
	<beans:bean id="accessDecisionManagerBean"
		class="com.gv.base.security.BaseAccessDecisionManager"></beans:bean>

	<!-- 资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色访问 -->
	<beans:bean id="securityMetadataSource"
		class="com.gv.base.security.FilterInvocationSecurityMetadataSourceImpl">
		<beans:constructor-arg name="dao" ref="dao"></beans:constructor-arg>
	</beans:bean>

	<!-- 定义国际化 -->
	<beans:bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<beans:property name="basename" value="classpath:message_zh_CN" />
	</beans:bean>

	<!-- 成功之后处理类 该类继承springsecurity 成功后的处理类 处理一些自己的操作后再交给 springsecurity成功后的处理类 
		跳转 -->
	<beans:bean id="baseSuccessHandler"
		class="com.gv.base.security.BaseAuthenticationSuccessHandler">
		<beans:property name="defaultTargetUrl" value="/mainfream/index_index.jsp"></beans:property>
		<beans:property name="alwaysUseDefaultTargetUrl" value="false"></beans:property>
	</beans:bean>
	<!-- cas中心认证服务入口 -->
	<beans:bean id="casEntryPoint"
		class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
		<beans:property name="loginUrl"
			value="http://127.0.0.1:8080/cas-server-webapp/login" />
		<beans:property name="serviceProperties" ref="serviceProperties" />
	</beans:bean>

	<!-- cas中心认证服务配置,登录成功后的返回地址 -->
	<beans:bean id="serviceProperties"
		class="org.springframework.security.cas.ServiceProperties">
		<beans:property name="service"
			value="http://127.0.0.1:8083/cas-client-webapp/j_spring_cas_security_check" />
		<beans:property name="sendRenew" value="false" />
	</beans:bean>

	<!-- CAS service ticket(中心认证服务凭据)验证 -->
	<beans:bean id="casFilter"
		class="org.springframework.security.cas.web.CasAuthenticationFilter">
		<beans:property name="authenticationManager" ref="authenticationManager" />
		<beans:property name="authenticationSuccessHandler"
			ref="authenticationSuccessHandler" />
		<beans:property name="authenticationFailureHandler"
			ref="authenticationFailureHandler" />
	</beans:bean>

	<!-- 登录成功处理器 -->
	<!-- <beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler"> -->
	<beans:bean id="authenticationSuccessHandler"
		class="com.gv.base.security.BaseCasAuthenticationSuccessHandler">
		<beans:property name="alwaysUseDefaultTargetUrl" value="true"></beans:property>
		<beans:property name="defaultTargetUrl" value="/mainfream/index_index.jsp"></beans:property>
	</beans:bean>

	<!-- 登录失败 -->
	<beans:bean id="authenticationFailureHandler"
		class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
		<beans:property name="defaultFailureUrl"
			value="http://127.0.0.1:8080/cas-server-webapp/login"></beans:property>
	</beans:bean>

	<authentication-manager alias="authenticationManager">
		<authentication-provider ref="casAuthenticationProvider" />
	</authentication-manager>

	<beans:bean id="casAuthenticationProvider"
		class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
		<beans:property name="authenticationUserDetailsService"
			ref="casAuthenticationUserDetailsService" />
		<beans:property name="serviceProperties" ref="serviceProperties" />
		<beans:property name="ticketValidator">
			<beans:bean
				class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
				<beans:constructor-arg index="0"
					value="http://127.0.0.1:8080/cas-server-webapp/" />
			</beans:bean>
		</beans:property>
		<beans:property name="key"
			value="an_id_for_this_auth_provider_only" />
	</beans:bean>

	<beans:bean id="casAuthenticationUserDetailsService"
		class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
		<beans:property name="userDetailsService">
			<beans:ref bean="userDetailsService" />
		</beans:property>
	</beans:bean>
	<!--客户端注销 -->
	<beans:bean id="singleLogoutFilter"
		class="org.jasig.cas.client.session.SingleSignOutFilter" />

</beans:beans>
配置文件中还有其它配置,是用来验证权限的,重点关注和CAS相类的配置即可

Spring Security还有别外的一种配置,在Spring Security上面有提供,是pre开头的配置方式

测试

在服务端的casGenericSuccess.jsp文件中,增加一个连接,连接到客户端,即可。
<jsp:directive.include file="includes/top.jsp" />
		<div id="msg" class="success">
			<h2><spring:message code="screen.success.header" /></h2>
			<p><spring:message code="screen.success.success" /></p>
			<p><spring:message code="screen.success.security" /></p>
		</div>
		<h1><a target="blank" href="http://127.0.0.1:8083/cas-client-webapp/mainfream/index_index.jsp">client</a></h1>
<jsp:directive.include file="includes/bottom.jsp" />







单点登录CAS与Spring Security集成(数据库验证,向客户端发送更多信息),古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。