1、开发以及使用cas单点登录已经一年多了,途中为满足功能需求在断断续续在修改cas源码,在此我建议,如果想自定义登入成功界面、密码修改、用户注册等功能,请单独开发一个web小工程,因为cas服务端(cas-server)的代码沉重,整个逻辑理解起来挺困难,还是制作一个小项目cas客户端(cas-client)方便,cas服务器(cas-server)只单纯做登录验证过程。(个人建议)
2、如果想在CAS Server 中获取登录账号名称
2.1、添加两个类
package com.esb.mydefined.util;
import javax.servlet.http.HttpServletRequest;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
public class GetLoginUserName {
/**
* 获取登入账号
* @param request
* @return
*/
public static String getLoginUserName(HttpServletRequest request) {
CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator = (CookieRetrievingCookieGenerator) SpringContextUtil.getBean("ticketGrantingTicketCookieGenerator");
TicketRegistry ticketRegistry = (TicketRegistry) SpringContextUtil.getBean("ticketRegistry");
String userName = null;
String serviceTicketId = ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
TicketGrantingTicket serviceTicket = (TicketGrantingTicket) ticketRegistry.getTicket(serviceTicketId);
if (serviceTicket != null && serviceTicket.isExpired() == false) {
userName = serviceTicket.getAuthentication().getPrincipal().getId();
}
return userName;
}
}
package com.esb.mydefined.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 获取注入的bean
* @author junfei_lu
*
*/
public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext; // Spring应用上下文环境
/*
* 实现了ApplicationContextAware 接口,必须实现该方法;
* 通过传递applicationContext参数初始化成员变量applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) throws BeansException {
return (T) applicationContext.getBean(clazz);
}
}
2.2、获取注入bean这个类添加在cas-servlet.xml中
<bean id="springContextUtil" class="com.esb.mydefined.util.SpringContextUtil" scope="singleton" />
2.3、在登入界面(casGenericSuccess.jsp)引入获取登录账号的方法并调用,这样就可以在页面上获取账号名了。
<%@page import="com.esb.mydefined.util.GetLoginUserName" %>
<%
String username = GetLoginUserName.getLoginUserName(request);
if(username == null){
username= request.getParameter("username");
}
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
</head>
<body>
<div><%=username%></div>
</body>
</html>