1到旦、cas項(xiàng)目下載
Cas項(xiàng)目可以在GitHub上下載亮曹,地址:https://github.com/apereo/cas/releases
本文以cas V4.0.0為例宵距,解壓后得到的是cas server的源碼然低,需要把目錄下的cas-server-webapp項(xiàng)目加載到idea中英遭。
2胁赢、配置cas項(xiàng)目的數(shù)據(jù)庫連接和去掉https請求
配置cas-server
修改%tomcat_home%/webapps/cas/WEB_INF/deployerConfigContext.xml
配置數(shù)據(jù)庫驗(yàn)證bean
<!-- 數(shù)據(jù)源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="minIdle" value="14400"/>
</bean>
修改authenticationManager
<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" />
</map>
</constructor-arg>
添加一個entry企蹭,primaryAuthenticationHandler。
創(chuàng)建自定義密碼校驗(yàn)處理類
<bean id="primaryAuthenticationHandler" class="com.imec.authentication.handler.MyAuthenticationHandler">
<property name="dataSource" ref="dataSource"/>
<property name="sql" value="SELECT password, salt, status FROM t_account_cas WHERE name=?"/>
</bean>
創(chuàng)建一個自定義的密碼校驗(yàn)類MyAuthenticationHandler,繼承AbstractJdbcUsernamePasswordAuthenticationHandler谅摄,
進(jìn)行密碼校驗(yàn)徒河。
@Override
protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential usernamePasswordCredential) throws GeneralSecurityException, PreventedException {
final String username = usernamePasswordCredential.getUsername();
final String password = usernamePasswordCredential.getPassword();
try {
final Map<String, Object> values = getJdbcTemplate().queryForMap(this.sql, username);
String dbPassword = (String) values.get("password");
String salt = (String) values.get("salt");
salt=username+salt;
Integer status = (Integer) values.get("status");
if(!status.equals(1)) { //判斷帳號是否被凍結(jié)
throw new AccountLockedException("This user is disabled.");
}
//密碼加鹽并迭代1024次
String encryptedPassword = new Md5Hash(usernamePasswordCredential.getPassword(), salt, 2).toHex();
if (!dbPassword.equals(encryptedPassword)) {
throw new FailedLoginException("Password does not match value on record.");
}
} catch (final IncorrectResultSizeDataAccessException e) {
if (e.getActualSize() == 0) {
throw new AccountNotFoundException(username + " not found with SQL query");
} else {
throw new FailedLoginException("Multiple records found for " + username);
}
} catch (final DataAccessException e) {
e.printStackTrace();
throw new PreventedException("SQL exception while executing query for " + username, e);
}
return createHandlerResult(usernamePasswordCredential, new SimplePrincipal(username), null);
}
去掉https驗(yàn)證
cas默認(rèn)是采用https模式的,我們沒有配置證書螟凭,所以去掉https驗(yàn)證取消https的過濾虚青,讓http協(xié)議也能訪問
4.0.0 版本一共需要修改三個地方
修改deployerConfigContext.xml添加p:requireSecure=”false”
cas/WEB-INF/deployerConfigContext.xml
<!-- Required for proxy ticket mechanism. -->
<bean id="proxyAuthenticationHandler"
class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
p:httpClient-ref="httpClient" p:requireSecure="false" />
修改ticketGrantingTicketCookieGenerator.xml修改p:cookieSecure=”false”
cas/WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml
<bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
p:cookieSecure="false"
p:cookieMaxAge="-1"
p:cookieName="CASTGC"
p:cookiePath="/cas" />
修改warnCookieGenerator.xml修改p:cookieSecure=”false”
cas/WEB-INF/spring-configuration/warnCookieGenerator.xml
<bean id="warnCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
p:cookieSecure="false"
p:cookieMaxAge="-1"
p:cookieName="CASPRIVACY"
p:cookiePath="/cas" />
3、spring security 和cas的集成
修改spring-sercurity.xml
1螺男、配置一個cas地址的properties文件棒厘。
#cas server login address
cas_server_login=http://localhost:8084/cas/login
#cas server login successful return localhost address
localhost_server=http://localhost:8080/nsycManager/j_spring_cas_security_check
#cas server ticket validator address
cas_server_address=http://localhost:8084/cas
#cas server logout successful return localhost address
cas_server_logout=http://localhost:8084/cas/logout?service=http://localhost:8080/nsycManager/login
2、設(shè)置spring sercurity的自動攔截設(shè)置為false下隧,配置一個進(jìn)入cas的認(rèn)證入口casAuthEntryPoint奢人。在攔截器里配置一個自定義的cas認(rèn)證過濾器、一個注銷客戶端和一個注銷session的服務(wù)器端的過濾器淆院。
<!-- cas地址配置 -->
<beans:bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<beans:property name="order" value="1"/>
<beans:property name="ignoreUnresolvablePlaceholders" value="true"/>
<beans:property name="location" value="classpath:cas.properties"/>
</beans:bean>
<!-- 不要過濾圖片等靜態(tài)資源 -->
<http pattern="/resources/**" security="none"/>
<!-- cas攔截規(guī)則 -->
<http auto-config="false" entry-point-ref="casAuthEntryPoint" servlet-api-provision="true">
<intercept-url pattern="login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
<session-management invalid-session-url="/login"/>
<!-- cas 認(rèn)證過濾器 -->
<custom-filter ref="casFilter" position="CAS_FILTER"/>
<!-- 注銷服務(wù)器端 -->
<custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>
<!-- 注銷客戶端 -->
<custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>
</http>
<!-- CAS認(rèn)證切入點(diǎn)何乎,聲明cas服務(wù)器端登錄的地址 -->
<beans:bean id="casAuthEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
<beans:property name="loginUrl" value="${cas_server_login}"/>
<beans:property name="serviceProperties" ref="casService"/>
</beans:bean>
<!-- 登錄成功后的返回地址 -->
<beans:bean id="casService" class="org.springframework.security.cas.ServiceProperties">
<beans:property name="service" value="${localhost_server}"/>
<beans:property name="sendRenew" value="false"/>
</beans:bean>
認(rèn)證入口里配置一個cas的登錄地址,和一個認(rèn)證成功后當(dāng)前項(xiàng)目的返回地址土辩。
3支救、配置cas認(rèn)證過濾器
<!-- cas 認(rèn)證過濾器 -->
<beans:bean id="casFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="authenticationFailureHandler" ref="authenticationFailureHandler"/>
<beans:property name="authenticationSuccessHandler" ref="authenticationSuccessHandler"/>
<beans:property name="filterProcessesUrl" value="/j_spring_cas_security_check"/>
</beans:bean>
<!-- 在認(rèn)證管理器中注冊cas認(rèn)證提供器 -->
<authentication-manager alias="authenticationManager">
<authentication-provider ref="casAuthenticationProvider"/>
</authentication-manager>
<!-- cas認(rèn)證提供器,定義客戶端的驗(yàn)證方式 -->
<beans:bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<beans:property name="ticketValidator" ref="casTicketValidator"/>
<beans:property name="serviceProperties" ref="casService"/>
<beans:property name="key" value="an_id_for_this_auth_provider_only"/>
<beans:property name="authenticationUserDetailsService" ref="authenticationUserDetailsService"/>
</beans:bean>
<!-- 配置ticket validator -->
<beans:bean id="casTicketValidator" class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<beans:constructor-arg index="0" value="${cas_server_address}"/>
</beans:bean>
<beans:bean id="authenticationUserDetailsService" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:property name="userDetailsService" ref="basicUserDetailsService"/>
</beans:bean>
<beans:bean id="basicUserDetailsService"
class="com.imec.air.ctrl.mgr.auth.security.authentication.BasicUserDetailsServiceImpl">
</beans:bean>
<!-- cas 認(rèn)證失敗控制器 -->
<beans:bean id="authenticationFailureHandler" class="com.imec.air.ctrl.mgr.auth.security.authentication.BasicAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/login.jsp?error=true"/>
</beans:bean>
<!-- cas 認(rèn)證成功控制器 -->
<beans:bean id="authenticationSuccessHandler" class="com.imec.air.ctrl.mgr.auth.security.authentication.BasicAuthenticationSuccessHandler">
</beans:bean>
配置一個攔截登錄請求的URL地址拷淘、配置一個cas認(rèn)證提供器各墨、配置認(rèn)證過濾器成功跳轉(zhuǎn)方法和失敗跳轉(zhuǎn)方法。其中cas認(rèn)證提供器里配置有cas的ticket的校驗(yàn)類casTicketValidator启涯、ticket認(rèn)證成功后返回的當(dāng)前項(xiàng)目的地址贬堵、校驗(yàn)方式和UserDetailsService的實(shí)現(xiàn)類。
4结洼、注銷客戶端過濾器
<!-- 注銷客戶端 -->
<beans:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" />
5黎做、注銷服務(wù)器端過濾器
<!-- 注銷服務(wù)器端 -->
<beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<!--<beans:property name="filterProcessesUrl" value="/j_spring_cas_security_logout"/>-->
<beans:constructor-arg value="${cas_server_logout}"/>
<beans:constructor-arg>
<beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</beans:constructor-arg>
<!--<beans:property name="filterProcessesUrl" value="/j_spring_cas_security_logout"/>-->
<beans:property name="filterProcessesUrl" value="/j_spring_cas_security_logout"/>
<!--<beans:property name="filterProcessesUrl" value="/cas/logout"/>-->
</beans:bean>
注銷服務(wù)器端的過濾器中,配置一個服務(wù)器的注銷地址和當(dāng)前項(xiàng)目退出操作的URL地址松忍。
注意:服務(wù)器的注銷地址中可以帶一個注銷成功后的回調(diào)地址蒸殿。
cas_server_logout=http://localhost:8084/cas/logout?service=http://localhost:8080/nsycManager/login
需要配置cas項(xiàng)目
WEB-INF/cas.properties文件 改成true
##
# CAS Logout Behavior
# WEB-INF/cas-servlet.xml
#
# Specify whether CAS should redirect to the specified service parameter on /logout requests
cas.logout.followServiceRedirects=true
注意:cas要和spring security集成,還需要添加spring-security-cas和cas-client-core這兩個架包鸣峭。
到此伟桅,spring sercurity和cas實(shí)現(xiàn)SSO單點(diǎn)登錄完成。