CAS SSO改造步骤(2)

设计完数据库之后就开始配置CAS server了。

至于CAS server 和CAS client的配置方法网上有很多种配置方法大致都是可行的个别版本不一样。

笔者这里使用的CAS server是3.5版本,Client是3.1版本。

JDK 7以及Tomcat 7。

配置的过程需要耐心一点。

你需要首先了解SSO工作的基本原理才能在源码的基础上改造,比如源码里面关于Spring文件的配置,关于数据库连接的接口部分等。

我们来看实际的代码吧。

<?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:sec="http://www.springframework.org/schema/security"
       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">
  <!--
    | 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">
    <!--
      | 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>

        <!--
          | 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" />
        <!--
          | 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 class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
          <property name="sql" value="select PASSWORD from GERSAUTH.USERS where EMAIL=?" />
          <property name="dataSource" ref="casDataSource" />
          <property name="passwordEncoder" ref="passwordEncoder"/>
        </bean> -->
        <bean class="org.jasig.cas.authentication.handler.support.AppRegisteredOrNotAuthenticationHandler"
          p:httpClient-ref="httpClient">
          <property name="queryDatabaseAuthenticationHandler" ref="queryDatabaseAuthenticationHandler"/>
          <property name="modifyLoginedStatusAttributeDAO" ref="modifyLoginedStatusAttributeDAO"/>
          <property name="applicationAuthoritiedAuthenticationDAO" ref="applicationAuthoritiedAuthenticationDAO"/>
        </bean>
      </list>
    </property>
  </bean>
  
  <!-- 
  	this bean defines the user login and log out status.
  -->
  <bean id="applicationAuthoritiedAuthenticationDAO" class="org.jasig.services.persondir.support.jdbc.ApplicationAuthoritiedAuthenticationDAO">
  	<constructor-arg index="0" ref="casDataSource"/>
  	<constructor-arg index="1">
  		<value>
  			SELECT COUNT(*) FROM APPLICATIONS 
  			WHERE APP_URL =? AND ID IN (select APP_ID FROM USER_APPS 
  			WHERE USER_ID = (SELECT ID FROM USERS WHERE EMAIL=?))
  		</value>
  	</constructor-arg>
  </bean>
  <bean id="modifyLoginedStatusAttributeDAO" class="org.jasig.services.persondir.support.jdbc.ModifyLoginedStatusAttributeDAO">
  	<constructor-arg index="0" ref="casDataSource"/>
  	<property name="updateSQL">
  		<value>
  			UPDATE USERS SET TOKEN=? WHERE EMAIL=?
  		</value>
  	</property>
  	<property name="selectSQL">
  		<value>
  			SELECT TOKEN FROM USERS WHERE EMAIL=?
  		</value>
  	</property>
  </bean>
  
  <bean id="queryDatabaseAuthenticationHandler" class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
          <property name="sql" value="select PASSWORD from GERSAUTH.USERS where EMAIL=?" />
          <property name="dataSource" ref="casDataSource" />
          <!--<property name="passwordEncoder" ref="passwordEncoder"/>-->
  </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">
      <list>
        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="0" />
          <property name="name" value="HTTP" />
          <property name="description" value="Only Allows HTTP Urls" />
          <property name="serviceId" value="http://**" />
          <property name="evaluationOrder" value="10000001" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
          <property name="allowedAttributes">
            <list>
              <value>id</value>
              <value>app_name</value>
              <value>app_url</value>
            </list>
          </property>
        </bean>

        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="1" />
          <property name="name" value="HTTPS" />
          <property name="description" value="Only Allows HTTPS Urls" />
          <property name="serviceId" value="https://**" />
          <property name="evaluationOrder" value="10000002" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
        </bean>

        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="2" />
          <property name="name" value="IMAPS" />
          <property name="description" value="Only Allows HTTPS Urls" />
          <property name="serviceId" value="imaps://**" />
          <property name="evaluationOrder" value="10000003" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
        </bean>

        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="3" />
          <property name="name" value="IMAP" />
          <property name="description" value="Only Allows IMAP Urls" />
          <property name="serviceId" value="imap://**" />
          <property name="evaluationOrder" value="10000004" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
        </bean>
      </list>
    </property>
</bean>

<bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />

<bean id="casDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.ibm.db2.jcc.DB2Driver</value>
</property>
<property name="url">
<value>jdbc:db2://9.115.46.188:50001/xxxx</value>
</property>
<property name="username">
<value>xxxx</value>
</property>
<property name="password">
<value>xxxxx</value>
</property>
</bean>

<bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDao">
<constructor-arg index="0" ref="casDataSource" />

<constructor-arg index="1">
<value>
  SELECT * FROM APPLICATIONS WHERE
    ID IN( SELECT APP_ID FROM USER_APPS
        WHERE USER_ID =( SELECT ID FROM USERS WHERE {0}))
</value>
</constructor-arg>

<property name="queryAttributeMapping">
<map>
  <entry key="username" value="EMAIL"/>
</map>
</property>
<property name="nameValueColumnMappings">
<map>
  <entry key="ID" value="id" />
  <entry key="APP_NAME" value="app_name" />
  <entry key="APP_URL" value="app_url" />
</map>
</property>
</bean>

</beans>

为deployerConfigContext.xml文件的更改内容。

红色部分为登录的时候验证用户名和密码以及用户是否登录,用户是否有访问该应用的权限等。

这里我们先看改动的地方。这里我新建了一个集成类然后将系统自带的QueryDatabaseAuthenticationHandler作为新建类AppRegisteredOrNotAuthenticationHandler的引用。

AppRegisteredOrNotAuthenticationHandler类的内容为:

 

public final class AppRegisteredOrNotAuthenticationHandler implements
		AuthenticationHandler {

	/** The string representing the HTTPS protocol. */
	private static final String PROTOCOL_HTTPS = "https";
	/** Log instance. */
	private final Logger log = LoggerFactory.getLogger(getClass());
	private HttpServletRequest httpServletRequest;
	/** Instance of Apache Commons HttpClient */

	/** Boolean variable denoting whether secure connection is required or not. */
	private boolean requireSecure = true;

	@NotNull
	private ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO;

	@NotNull
	private ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO;
	/** Instance of Apache Commons HttpClient */
	@NotNull
	private HttpClient httpClient;

	private QueryDatabaseAuthenticationHandler queryDatabaseAuthenticationHandler;

	/**
	 * authentication username and password. everytime check whether user has
	 * logged in other place update login status ,change token =1, then
	 * authenticate the url requested is valid or not.
	 * */
	public boolean authenticate(final Credentials credentials) {
		final UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials) credentials;
		try {
			boolean userinfoAuth = this.getQueryDatabaseAuthenticationHandler()
					.authenticate(userinfo);
			if (!userinfoAuth) {
				return false;
			}
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			log.error("Authentication username and password Database wrong!");
		}
		try {
			boolean status = this.modifyLoginedStatusAttributeDAO
					.CheckLogged(userinfo.getUsername());
			if (status) {
				return false;
			}
			String url = this.httpServletRequest.getParameter("service");
			// get the main domain and port from url
			boolean result = this.applicationAuthoritiedAuthenticationDAO
					.CheckApplicationURLIsAuthority(url, userinfo.getUsername());
			if (result) {
				log.debug("this Application not exist!");
				return false;
			}
			// change token state
			this.modifyLoginedStatusAttributeDAO.updateToken(
					userinfo.getUsername(), "1");

		} catch (Exception e) {
			log.error("update token error");
		}
		return true;
	}

	/**
	 * @return true if the credentials provided are not null and the credentials
	 *         are a subclass of (or equal to) HttpBasedServiceCredentials.
	 */
	public boolean supports(final Credentials credentials) {
		return credentials != null;
	}

	public void setQueryDatabaseAuthenticationHandler(
			QueryDatabaseAuthenticationHandler queryDatabaseAuthenticationhandler) {
		this.queryDatabaseAuthenticationHandler = queryDatabaseAuthenticationhandler;
	}

	public QueryDatabaseAuthenticationHandler getQueryDatabaseAuthenticationHandler() {
		return queryDatabaseAuthenticationHandler;
	}

	/** Sets the HttpClient which will do all of the connection stuff. */
	public void setHttpClient(final HttpClient httpClient) {
		this.httpClient = httpClient;
	}

	/**
	 * Set whether a secure url is required or not.
	 * 
	 * @param requireSecure
	 *            true if its required, false if not. Default is true.
	 */
	public void setRequireSecure(final boolean requireSecure) {
		this.requireSecure = requireSecure;
	}

	@Override
	public void setHttpServletRequest(HttpServletRequest request) {
		// TODO Auto-generated method stub
		this.httpServletRequest = request;
	}

	public void setModifyLoginedStatusAttributeDAO(
			ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO) {
		this.modifyLoginedStatusAttributeDAO = modifyLoginedStatusAttributeDAO;
	}

	public ModifyLoginedStatusAttributeDAO getModifyLoginedStatusAttributeDAO() {
		return modifyLoginedStatusAttributeDAO;
	}

	public void setApplicationAuthoritiedAuthenticationDAO(
			ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO) {
		this.applicationAuthoritiedAuthenticationDAO = applicationAuthoritiedAuthenticationDAO;
	}

	public ApplicationAuthoritiedAuthenticationDAO getApplicationAuthoritiedAuthenticationDAO() {
		return applicationAuthoritiedAuthenticationDAO;
	}

}

代码中蓝色的几个私有变量第一个是HttpServletRequest是从认证中心传进来的变量,主要是获取Service URL添加的。

其他三个都是与数据库操作有关的。

红色部分逻辑是:首先验证用户名密码是否合法,然后再验证该用户是否已经登录,再验证用户访问的APP是否是授权的,最后如果都正确那么将登录状态更改为1;

其他几个修改的类如下:

ModifyLoginedStatusAttributeDAO.java

package org.jasig.services.persondir.support.jdbc;

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

import javax.sql.DataSource;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.Assert;


public class ModifyLoginedStatusAttributeDAO   {

	 private final Logger log = LoggerFactory.getLogger(this.getClass());
	 /** set data source*/
	 private final DataSource dataSource;
	 private final SimpleJdbcTemplate jdbcTemplate;
	 /** set update format */
	 private String updateSQL;
	 /** set select sql format. */
	 private String selectSQL;
	 
	 public ModifyLoginedStatusAttributeDAO(DataSource dataSource){
		 Assert.notNull(dataSource,"dataSource should be initinal");
		 this.dataSource = dataSource;
		 this.jdbcTemplate = new SimpleJdbcTemplate(this.dataSource);
	 }
	 /** this method change logged status when user log in or log out. */
	 public void updateToken(String username,String value){
		 Assert.notNull(username, "username cannot be null");
		 Assert.notNull(value,"update value cannot be null");
		 
		 Object[] obj = {value,username};
		 try{
			 this.jdbcTemplate.update(this.updateSQL, obj);
		 }catch(Exception e){
			 log.error("update token error.");
		 }
	 }
	 /** this method complete authenticating the user is logged in one place.*/
	public boolean CheckLogged(String username){
		Validate.notNull(username, "username should not be null");
		String result=null;
		try{
			 result = this.jdbcTemplate.queryForObject(this.selectSQL, String.class, username);
		}catch(Exception e){
			log.error("select database error!");
		}
		if(result.equals("1")){
			return true;
		}
		return false;
	}
	public void setUpdateSQL(String updateSQL) {
		this.updateSQL = updateSQL;
	}
	public void setSelectSQL(String selectSQL) {
		this.selectSQL = selectSQL;
	}

}

ApplicationAuthoritiedAuthenticationDAO.java

代码如下:

package org.jasig.services.persondir.support.jdbc;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.sql.DataSource;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.Assert;

public class ApplicationAuthoritiedAuthenticationDAO {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	/** set data source */
	@NotNull
	private final DataSource dataSource;
	@NotNull
	private final SimpleJdbcTemplate jdbcTemplate;

	/** set select sql format. */
	@NotNull
	private String sql;

	public ApplicationAuthoritiedAuthenticationDAO(DataSource dataSource,
			String sql) {
		Assert.notNull(dataSource, "dataSource should be not null");
		Assert.notNull(sql, "sql statement should not be null");
		this.dataSource = dataSource;
		this.jdbcTemplate = new SimpleJdbcTemplate(this.dataSource);
		this.sql = sql;
	}

	/** check this url is valid for this user */
	public boolean CheckApplicationURLIsAuthority(String url, String username) {
		Assert.notNull(url, "url cannot be null.");
		Assert.notNull(username, "username is null");

		Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-:]+/[\\w]+/"); 
		Matcher matcher = pattern.matcher(url); 
		StringBuffer buffer = new StringBuffer(); 
		matcher.find();            
		buffer.append(matcher.group());                   
		url = buffer.toString(); 

		Object[] param = { url, username };
		int result = -1;
		result = this.jdbcTemplate.queryForInt(sql, param);
		if (result < 1) {
			log.debug("this Application not exist!");
			return true;
		}
		return false;
	}
}


上面是登录验证功能里面涉及到的几个类。

下一节将介绍其他部分的功能。不过其他部分的功能数据库操作部分引用以上几个类的代码。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值