CAS单点登陆更改认证方式和持久化ticket

[转载]cas 入门之十五:ticket 存储方案-jpa ticket存储

基于以上,有一些问题处理.

CAS3.5.2.1

修改认证方式 deployerConfigContext.xml

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


    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.


-->
<!--
| 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>
<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver" >
<property name="attributeRepository" ref="attributeRepository" />
</bean>
<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">
<!-- 以下3中验证方式有一种通过即可 -->
<list>
<!-- <bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
p:httpClient-ref="httpClient" /> -->
<bean  class="com.infohold.ecif.EcifQueryDatabastAuthenticationHandler">
<property name="dataSource" ref="dataSource" ></property>  
<property name="passwordEncoder" ref="passwordEncoder"></property>
</bean>

</list>
</property>
</bean>

<!-- mysql连接 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean> 
<bean id="passwordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder">
<constructor-arg value="MD5" />
</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.jdbc.SingleRowJdbcPersonAttributeDao">
<constructor-arg index="0" ref="dataSource" />
<constructor-arg index="1" value="SELECT u.user_id ,u.login_id FROM auth_user u where {0} "/>
<property name="queryAttributeMapping">
<map>
<entry key="username" value="u.user_id" />
</map>
</property>
<property name="resultAttributeMapping">
<map>
<entry key="user_id" value="user_id" />
<entry key="login_id" value="login_id" />
</map>
</property>
</bean>
<!-- <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.JpaServiceRegistryDaoImpl"
p:entityManagerFactory-ref="entityManagerFactory"> 
</bean>
  -->
<bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
            <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" />
                        <property name="allowedAttributes">
                        <list>
                        <value>user_id</value>
                        <value>login_id</value>
                        </list>
                        </property>
                    </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.infohold.ecif;


import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;


import net.sf.json.JSONObject;


import org.apache.log4j.Logger;
import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.dao.DataAccessException;


/**
 * Cas 登录信息验证Handler
 * @author wanglei
 *
 */
@SuppressWarnings("deprecation")
public class EcifQueryDatabastAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler{

private Logger logger = Logger.getLogger(EcifQueryDatabastAuthenticationHandler.class);


//校验用户信息SQL
final String check_sql = "SELECT * FROM auth_user u where u.login_id = ? ";
//CAS登录-查询用户信息
final String query_user_sql="SELECT "
+ "  u.user_id,"
+ "  u.login_id,"
+ "  u.user_name,"
+ "  u.tel_no,"
+ "  u.status,"
+ "  o.org_id,"
+ "  o.org_name "
+ " FROM "
+ "  auth_user u,"
+ "  auth_organization o "
+ " WHERE u.org_id = o.org_id "
+ "    AND u.status <> 2 "
+ "    AND u.user_id =  ?"
;
//查询角色信息SQL
String query_role_sql ="SELECT "
+ "  r.role_id,"
+ "  r.role_name "
+ " FROM "
+ "  auth_user u,"
+ "  auth_user_role_ref ur,"
+ "  auth_role r "
+ "WHERE u.user_id = ur.user_id "
+ "  AND ur.role_id = r.role_id "
+ "  AND u.user_id = ? ";
//查询会计日期
final String query_sysdate_sql = "select value_ AS sysdate from sys_parameter_cfg a where a.key_ ='system_date'";
@Override
protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials) throws AuthenticationException {

final String username = getPrincipalNameTransformer().transform(credentials.getUsername());

final String password = credentials.getPassword();

final String encryptedPassword = this.getPasswordEncoder().encode(password);
if(username==null||"".equals(username)||password==null||"".equals(password)){
throw new AuthenticationException(("用户/密码不允许为空!")){
private static final long serialVersionUID = 8332664732922045828L;
};
} else{
Map<String, Object> register;
try {
register = getJdbcTemplate().queryForMap(this.check_sql,username);

final String login_pwd = (String) register.get("user_password");
final String user_id = (String) register.get("user_id");
String str="";
if(login_pwd.equals(encryptedPassword)){
//查询用户
List<Map<String, Object>> userList =getJdbcTemplate().queryForList(this.query_user_sql,user_id);
if (userList.isEmpty()) {
throw new AuthenticationException(("用户信息存在异常,请联系管理员!")){
private static final long serialVersionUID = 8332664732922045828L;
};
} else {
// 查询用户角色信息
List<Map<String, Object>> roleList =getJdbcTemplate().queryForList(this.query_role_sql,user_id);
List<Map<String, Object>> sysList =getJdbcTemplate().queryForList(this.query_sysdate_sql);
//查询会计日期
//拼装session
Map<String,Object> map=userList.get(0);
map.put("roleList", roleList);
map.put("sysdate", sysList.get(0).get("sysdate")+"");
//System.out.println(map.get("user_name")+"");
str=this.parseMapToJSON(map);
}
logger.info("用户信息:"+str);
byte[] s;
try {
s = str.getBytes("UTF-8");
String ss=new sun.misc.BASE64Encoder().encode(s);
credentials.setUsername(ss);
} catch (UnsupportedEncodingException e) {
logger.info(e);
}
return true;
}else{
throw new AuthenticationException(("密码输入错误,请重新输入!")){
private static final long serialVersionUID = 8332664732922045828L;
};
}
} catch (DataAccessException e) {
logger.info(e);
return false;
}
}
}

/**
     * 将MAP对象转换成JSON字符串
     * @param map
     * @return
     */
    public String parseMapToJSON(Map<String, Object> map){  
        JSONObject str=JSONObject.fromObject(map);
        String data=str.toString().replace("\"","'");
        return data;
    }  

}

持久化ticket

增加src/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
http://java.sun.com/xml/ns/persistence/persistence_version=1">
<persistence-unit name="mysqlJPA" transaction-type="RESOURCE_LOCAL">
<!-- <properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="${jdbc.driverClass}" />
<property name="hibernate.connection.username" value="${jdbc.user}" />
<property name="hibernate.connection.password" value="${jdbc.password}" />
<property name="hibernate.connection.url" value="${jdbc.jdbcUrl}" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.max_fetch_depth" value="600" />

</properties> -->
<class>org.jasig.cas.services.AbstractRegisteredService</class>
<class>org.jasig.cas.services.RegexRegisteredService</class>
<class>org.jasig.cas.services.RegisteredServiceImpl</class>
<class>org.jasig.cas.ticket.TicketGrantingTicketImpl</class>
<class>org.jasig.cas.ticket.ServiceTicketImpl</class>
<class>org.jasig.cas.ticket.registry.support.JpaLockingStrategy$Lock
</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
</properties>
</persistence-unit>
</persistence>  

修改 ticketRegistry.xml

<?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:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
            ">
    <description>
        Configuration for the default TicketRegistry which stores the tickets in-memory and cleans them out as specified intervals.
    </description>
    <!-- Ticket Registry -->
    <bean id="ticketRegistry" class="org.jasig.cas.ticket.registry.JpaTicketRegistry"></bean>
     <!--  让@PersistenceUnit and @PersistenceContext 自动注入 EntityManager/Factory 实例 -->
  <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
 
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true" />
                <property name="showSql" value="true" />
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
        p:entityManagerFactory-ref="entityManagerFactory" />
    <tx:annotation-driven transaction-manager="transactionManager" />
  
   <!-- mysql连接 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean> 
    
    <!-- Ticket Registry -->
    <!-- 默认的ticket registry,放内存里CAS服务器端改造
    <bean id="ticketRegistry" class="org.jasig.cas.ticket.registry.DefaultTicketRegistry" />
    -->
    <!-- 在集群环境,多个cas 服务器共享同一个数据库节点,当需要清理ticket时,会出现表争用,
但是cas通过cleanerLock解决了这个问题,同时并不会影响应用的性能。 -->
<bean id="cleanerLock" class="org.jasig.cas.ticket.registry.support.JpaLockingStrategy"
            p:uniqueId="${host.name}"
            p:applicationId="cas-ticket-registry-cleaner"/>
     
    <!--Quartz -->
    <!-- TICKET REGISTRY CLEANER -->
    <bean id="ticketRegistryCleaner" class="org.jasig.cas.ticket.registry.support.DefaultTicketRegistryCleaner"
        p:ticketRegistry-ref="ticketRegistry" 
        p:lock-ref="cleanerLock"/>
    


    <bean id="jobDetailTicketRegistryCleaner" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"
        p:targetObject-ref="ticketRegistryCleaner"
        p:targetMethod="clean" />
    
  <bean id="triggerJobDetailTicketRegistryCleaner" class="org.springframework.scheduling.quartz.SimpleTriggerBean"
        p:jobDetail-ref="jobDetailTicketRegistryCleaner"
        p:startDelay="20000"
        p:repeatInterval="5000000" /> 
        
</beans>


增加jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://****3306/portal?characterEncoding=utf8
jdbc.user=a
jdbc.password=a

server 地址: http://www.jasig.org/cas/download client 地址: http://www.ja-sig.org/downloads/cas-clients/ 当前最新版本 cas-server-3.4.2 , cas-client-3.1.10 2. 安装 server l 解压 cas-server-3.4.2 ,将 cas-server-3.4.2\modules\cas-server-webapp-3.4.2.war 拷贝到 tomcat 的 webapps 下。 3. 配置 server 3.1. 添加 cas server 依赖的 jar n cas-server-3.4.2\modules\cas-server-support-jdbc-3.4.2.jar 、 cas-server-integration-restlet-3.4.2.jar 拷贝到 D:\server\apache-tomcat-6.0.18\webapps\cas\WEB-INF\lib 目录下。 n 数据库驱动 jar 拷贝到 D:\server\apache-tomcat-6.0.18\webapps\cas\WEB-INF\lib 目录下。 n 到 apache 网站下载下面三个 cas server 依赖 jar 包拷贝到 D:\server\apache-tomcat-6.0.18\webapps\cas\WEB-INF\lib 目录下 Ø http://apache.freelamp.com/commons/collections/binaries/commons-collections-3.2.1-bin.zip Ø http://apache.etoak.com/commons/dbcp/binaries/commons-dbcp-1.4-bin.zip Ø http://apache.etoak.com/commons/pool/binaries/commons-pool-1.5.4-bin.zip n 下载 restlet 相关 http://www.restlet.org/downloads/ , 解压后将下面 jar 拷贝到 D:\server\apache-tomcat-6.0.18\webapps\cas\WEB-INF\lib: ( 它奶奶地这一步骤很折腾 ) com.noelios.restlet.ext.servlet_2.5.jar com.noelios.restlet.ext.spring_2.5.jar com.noelios.restlet.jar org.restlet.ext.spring_2.5.jar org.restlet.jar n 下载 CGlib http://sourceforge.net/projects/cglib/files/ 拷贝到 D:\server\apache-tomcat-6.0.18\webapps\cas\WEB-INF\lib 。 n 下载 ASM/OW2 http://forge.ow2.org/projects/asm/ 拷贝到 D:\server\apache-tomcat-6.0.18\webapps\cas\WEB-INF\lib 。 3.2. 添加数据源
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值