---
title: "CZTZ-JavaEE Web应用开发平台介绍之四--与CAS单点登录集成"
author: "cjc"
date: "2007-12-25T17:41:00Z"
tags: []
slug: "cztz-javaee-web-cas"
draft: false
lastmod: "2007-12-25T17:41:00Z"
id: 446912
url: "https://cjc.iteye.com/blog/446912"
---

CZTZ-JavaEE Web应用开发平台与CAS的单点登录产品进行了集成,CAS单点登录产品的默认的认证类是SimpleTestUsernamePasswordAuthenticationHandler,这个类的实现是当用户名和口令相等时认证通过,所以这个类肯定不能在生产环境使用的,现在需要将此类替换掉,实现一个基于数据库访问的认证方式.本文讲述如何实现这个类(数据源在tomcat中如何配置从略,我想大家都知道配置方式).

在CAS的WEB-INF目录下有个deployerConfigContext.xml文件,将&lt;bean  
class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" /&gt;改为

&lt;bean  
class="org.jasig.cas.authentication.handler.support.CasDaoAuthenticationHandler" /&gt;

其中CasDaoAuthenticationHandler是我自己开发的实现类,代码如下:

package org.jasig.cas.authentication.handler.support;

import java.sql.Connection;  
import java.sql.ResultSet;

import javax.naming.Context;  
import javax.naming.InitialContext;  
import javax.sql.DataSource;

import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;

public final class CasDaoAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler  
{  
public CasDaoAuthenticationHandler()  
{  
}

public boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials)  
{  
boolean bool = false;  
String username = credentials.getUsername();  
String password = credentials.getPassword();  
System.out.println("开始CAS认证......");  
System.out.println("userName:"+username);  
System.out.println("password:"+password);  
//首先连接权限数据库  
try  
{  
DataSource ds = null;  
InitialContext ctx=new InitialContext();  
Context contx = (Context)ctx.lookup("java:comp/env");  
ds = (DataSource) contx.lookup("jdbc/mysql");  
Connection con = ds.getConnection();  
if(con == null)  
System.out.println("con is null");

String sql = "select count(\*) from eas\_login\_user where user\_id='"+username+"' and user\_password='"+password+"'";  
ResultSet res = con.prepareStatement(sql).executeQuery();  
while(res.next())  
{  
int i = Integer.parseInt(res.getObject(1).toString());  
if(i&gt;0)  
{  
System.out.println("认证成功!");  
bool = true;  
break;  
}  
}  
con.close();  
}  
catch(Exception ex)  
{  
ex.printStackTrace();  
System.out.println("数据库连接失败!");  
return bool;  
}

return bool;  
}

protected void afterPropertiesSetInternal()  
throws Exception  
{  
super.afterPropertiesSetInternal();  
}

}

上面的代码是取CAS登录页面的用户名和口令到数据库检验是否存在用户名和口令相同的记录,当然在生产环境中

用户口令是加密存储的,所以实际应用中增加一个加密算法就可以了.

欢迎大家继续关注CZTZ-JavaEE Web应用开发平台!