Spring Security结合CAS的配置

原创
2014/03/18 10:06
阅读数 6.1K
在我的几个项目里需要用到单点登录,我选用了CAS,下面给出一个一般性的Spring Security结合CAS的配置文件
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	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.0.xsd
	
	http://www.springframework.org/schema/context
 	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/util/spring-util.xsd
 	http://www.springframework.org/schema/util/spring-util-3.0.xsd">
	
	<!--
		Enable security, let the casAuthenticationEntryPoint handle all
		intercepted urls. The CAS_FILTER needs to be in the right position within
		the filter chain.
	-->
	<security:http auto-config="true" entry-point-ref="casAuthenticationEntryPoint" path-type="regex">
		<security:port-mappings>
			<security:port-mapping http="${portHttp}" https="${portHttps}"/>
		</security:port-mappings>
		<security:logout success-handler-ref="simpleUrlLogoutSuccessHandler" />
		
		<security:intercept-url pattern="/.*" requires-channel="https" />
		<security:intercept-url pattern="(/admin/){1}\S*" access="ROLE_ADMIN" />
		<security:intercept-url pattern="/{1}\S*" access="ROLE_USER, ROLE_ADMIN" />
		<security:intercept-url pattern="(/api/ws/){1}\S*" filters="none" />
		<security:custom-filter position="CAS_FILTER" ref="casAuthenticationFilter" />
	</security:http>

	<!--
		似乎casFilter与casEntryPoint的功能有重叠。其实,casEntryPoint只是提供认证入口的作用,当没有登录,将跳转到该地址。 
		The entryPoint intercepts all the CAS authentication requests. It
		redirects to the CAS loginUrl for the CAS login page.
	-->
	<bean id="casAuthenticationEntryPoint"
		class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
		<property name="loginUrl" value="${casAuthenticationEntryPoint.loginUrl}" />
		<property name="serviceProperties" ref="serviceProperties" />
	</bean>
	
	<!-- 注销的url是/j_spring_security_logout -->

	<!--
		The CAS filter handles the redirect from the CAS server and starts the
		ticket validation.
		casFilter是处理CAS service ticket的。
	-->
	<bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
		<property name="authenticationManager" ref="authenticationManager" />
	</bean>
	

	<!--
		Required for the casProcessingFilter, so define it explicitly set and
		specify an Id Even though the authenticationManager is created by default
		when namespace based config is used.
	-->
	<security:authentication-manager alias="authenticationManager">
		<security:authentication-provider ref="casAuthenticationProvider" />
	</security:authentication-manager>

	<!-- 
		Handles the CAS ticket processing.
	 -->
	<bean id="casAuthenticationProvider"
		class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
		<property name="serviceProperties" ref="serviceProperties" />
		<property name="authenticationUserDetailsService" ref="authenticationUserDetailsService" />
		<property name="ticketValidator">
			<bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
				<constructor-arg index="0" value="${casAuthenticationProvider.casServerUrlPrefix}" />
			</bean>
		</property>
		<property name="key" value="${casAuthenticationProvider.key}" />
	</bean>

	<!--
		你需要添加一个 ServiceProperties bean,到你的application context里。 这表现你的CAS服务。
		这里的service必须是一个由CasAuthenticationFilter监控的URL。 这个sendRenew默认是false,但如果你的程序特别敏感就应该设置成true。 这个参数作用是,告诉CAS登录服务,一个单点登录没有到达。 否则,用户需要重新输入                他们的用户名和密码,来获得访问服务的权限。
	-->
	<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
		<property name="service" value="${serviceProperties.service}" />
	</bean>
  	
  	<bean id="authenticationUserDetailsService" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
  		<property name="userDetailsService" ref="jdbcUserDetailsService" />
  	</bean>
  	<security:jdbc-user-service data-source-ref="ucDataSource" id="jdbcUserDetailsService" authorities-by-username-query="${jdbcUserDetailsService.authoritiesByUsernameQuery}" />
  	
  	<bean id="simpleUrlLogoutSuccessHandler" class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
  		<property name="alwaysUseDefaultTargetUrl" value="true" />
  		<property name="defaultTargetUrl" value="${simpleUrlLogoutSuccessHandler.defaultTargetUrl}" />
  	</bean>
  	
</beans>

附加说明:


  • 这里我使用的是数据库保存授权信息的方式,因此使用了jdbc-user-service:(在我的项目里数据库名叫“uc”,下面给出数据库结构吧)
    DROP TABLE IF EXISTS `uc`.`users`;
    CREATE TABLE  `uc`.`users` (`username` varchar(32) NOT NULL, `password` varchar(255) NOT NULL DEFAULT '', `enabled` bit(1) NOT NULL DEFAULT b'1', PRIMARY KEY (`username`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    DROP TABLE IF EXISTS `uc`.`authorities`;
    CREATE TABLE  `uc`.`authorities` (`username` varchar(32) NOT NULL, `application_context` varchar(32) NOT NULL, `authority` varchar(32) NOT NULL, PRIMARY KEY (`username`,`authority`,`application_context`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    DROP TABLE IF EXISTS `uc`.`persistent_logins`;
    CREATE TABLE `uc`.`persistent_logins` ( `username` varchar(32) NOT NULL, `series` varchar(255) NOT NULL, `token` varchar(255) NOT NULL, `last_used` datetime NOT NULL, PRIMARY KEY (`series`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;


  • data-source-ref="ucDataSource"里面的ucDataSource是我项目里Spring Security保存授权信息的数据库的数据源,到时候换成你自己的就行

顺便吐槽一下这个代码高亮,每一行就不能长点吗,弄得代码都一坨了

展开阅读全文
打赏
1
10 收藏
分享
加载中
usersByUsernameQuery这个会遇到org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [select t.user_pwd from t_userinfo t where t.user_state='0' and t.user_name=? ]; Column Index out of range, 2 > 1. ; nested exception is java.sql.SQLException: Column Index out of range, 2 > 1. ,请问该如何解决呢
2016/09/22 10:09
回复
举报
<bean id="userDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<property name="dataSource" ref="dataSource" />
<property name="usersByUsernameQuery" value="select t.user_pwd from t_userinfo t where t.user_state='0' and t.user_name=? "/>
</bean>
2016/09/22 10:07
回复
举报

<bean id="casAuthenticationProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<!-- 通过username来加载UserDetails -->
<property name="authenticationUserDetailsService">
<bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<!-- 真正加载UserDetails的UserDetailsService实现 -->
<constructor-arg ref="userDetailsService" />
</bean>
</property>
<property name="serviceProperties" ref="serviceProperties" />
<!-- 配置TicketValidator在登录认证成功后验证ticket -->
<property name="ticketValidator">
<bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<!-- Cas Server访问地址的前缀,即根路径-->
<constructor-arg index="0" value="https://cas.server.com:8443/cas" />
</bean>
</property>
<property name="key" value="key4CasAuthenticationProvider" />
</bean>
2016/09/22 10:07
回复
举报
  <bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="url"
value=""/>
<property name="username" value="" />
<property name="password" value="" />
</bean>
  <!-- Automatically receives AuthenticationEvent messages -->
   <bean id="loggerListener"
      class="org.springframework.security.access.event.LoggerListener" />
  
    <bean id="authenticationEntryPoint"
class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
<property name="realmName" value="Pentaho Realm" />
</bean>
   <security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="casAuthenticationProvider" />
</security:authentication-manager>
</beans>
2016/05/26 14:44
回复
举报
<property name="serviceProperties" ref="serviceProperties" />
    <property name="ticketValidator" ref="ticketValidator" />
    <property name="key"
      value="my_password_for_this_auth_provider_only" />
  </bean>

<bean id="userDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="authoritiesByUsernameQuery">
<value>
</value>
</property>
<property name="usersByUsernameQuery">
<value>


</value>
</property>
</bean>
2016/05/26 14:44
回复
举报
  <bean id="exceptionTranslationFilter"
    class="org.springframework.security.web.access.ExceptionTranslationFilter">
    <property name="authenticationEntryPoint">
      <ref bean="casProcessingFilterEntryPoint" />
    </property>
    <property name="accessDeniedHandler">
      <bean class="org.springframework.security.web.access.AccessDeniedHandlerImpl" />
    </property>
  </bean>
  
  <bean id="casProcessingFilterEntryPoint"
    class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
    <property name="loginUrl"
      value="http://HOSTNAME:PORT/cas/login" />
    <property name="serviceProperties" ref="serviceProperties" />
  </bean>
  
<bean id="ticketValidator"
    class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<constructor-arg index="0" value="http://localhost:81/cas" />
  </bean>
<bean id="casAuthenticationProvider"
    class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
    <property name="userDetailsService" ref="userDetailsService" />
2016/05/26 14:43
回复
举报
  <bean id="exceptionTranslationFilter"
    class="org.springframework.security.web.access.ExceptionTranslationFilter">
    <property name="authenticationEntryPoint">
      <ref bean="casProcessingFilterEntryPoint" />
    </property>
    <property name="accessDeniedHandler">
      <bean class="org.springframework.security.web.access.AccessDeniedHandlerImpl" />
    </property>
  </bean>
  
  <bean id="casProcessingFilterEntryPoint"
    class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
    <property name="loginUrl"
      value="http://HOSTNAME:PORT/cas/login" />
    <property name="serviceProperties" ref="serviceProperties" />
  </bean>
  
<bean id="ticketValidator"
    class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<constructor-arg index="0" value="http://localhost:81/cas" />
  </bean>
<bean id="casAuthenticationProvider"
    class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
    <property name="userDetailsService" ref="userDetailsService" />
2016/05/26 14:43
回复
举报
<property name="service"
value="http://HOSTNAME:PORT/saiku/j_spring_cas_security_check"/>
<property name="sendRenew" value="false"/>
</bean>

<bean id="casEntryPoint"
class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
<property name="loginUrl" value="http://HOSTNAME:PORT/cas/login"/>
<property name="serviceProperties" ref="serviceProperties"/>
</bean>


  <bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager" />
<property name="authenticationFailureHandler">
<bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/casFailed.jsp" />
</bean>
</property>
</bean>

  
2016/05/26 14:42
回复
举报
你好,我想把一个应用(saiku)加进系统里,系统是CAS做的单点登录,这个应用是用的Spring Security,不知道改怎么配置,可以帮我看一下吗?谢谢。应用的ApplicationContext-spring-security-cas.xml代码如下,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

  <bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
   <!-- After login, return to the last visited page -->
   <property name="useReferer" value="true" />
  </bean>
  
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">

2016/05/26 14:42
回复
举报
更多评论
打赏
9 评论
10 收藏
1
分享
返回顶部
顶部