構造CAS客戶端的登入Servlet
根據CAS客戶端的Filter我們可以改造出一個具有同樣驗證功能的Servlet出來,改造後的程式碼如下:
public class CasLogin extends HttpServlet {
//*********************************************************************
// Constants
public final static String CAS_FILTER_USER = "edu.yale.its.tp.cas.client.filter.user";
/** Session attribute in which the username is stored */
private ServletConfig config;
private String casLogin,casValidate,casAuthorizedProxy,casServiceUrl,casRenew,casServerName;
private String redirectURL;
private String desktopURL;
private AuthHandler handler;
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.config = config;
try {
// create an instance of the right authentication handler
String handlerName =config.getInitParameter("com.longshine.sso.cas.authHandler");
if (handlerName == null)
throw new ServletException(" [啟動異常] 引數 com.longshine.sso.cas.authHandler 搜尋失敗!");
handler = (AuthHandler) Class.forName(handlerName).newInstance();
if (!(handler instanceof TrustHandler)){
throw new ServletException("unrecognized handler type: " + handlerName);
}else{
String suc = config.getInitParameter("edu.yale.its.tp.cas.casLoginSuccessCode");
AuthCodeRepository.updateSucCode(Integer.parseInt(suc),handler);
}
} catch (InstantiationException ex) {
throw new ServletException(ex.toString());
} catch (ClassNotFoundException ex) {
throw new ServletException(ex.toString());
} catch (IllegalAccessException ex) {
throw new ServletException(ex.toString());
}
//retrieve a relative URL for the CasLogin Servlet
this.casLogin = config.getInitParameter("edu.yale.its.tp.cas.casLogin");
this.casValidate = config.getInitParameter("edu.yale.its.tp.cas.casValidate");
this.casServerName = config.getInitParameter("edu.yale.its.tp.cas.serverName");
this.casServiceUrl = config.getInitParameter("edu.yale.its.tp.cas.client.filter.serviceUrl");
this.casAuthorizedProxy = config.getInitParameter("edu.yale.its.tp.cas.client.filter.authorizedProxy");
this.casRenew = config.getInitParameter("edu.yale.its.tp.cas.client.filter.renew");
this.redirectURL = config.getInitParameter("edu.yale.its.tp.cas.redirectURL");
this.desktopURL = config.getInitParameter("edu.yale.its.tp.cas.desktopURL");
if (casLogin == null || casValidate == null ||
casServerName == null || redirectURL == null ||
desktopURL == null)
throw new ServletException("[啟動異常] 請配置如下必要引數: edu.yale.its.tp.cas.casLogin, "
+ "-casValidate, -serverName, -redirectURL, and -desktopURL ");
}
// *********************************************************************
// Request handling
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//avoid caching (in the stupidly numerous ways we must)
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",-1);
HttpSession session = request.getSession();
// if our attribute's already present, don't do anything
if (session != null && session.getAttribute(CAS_FILTER_USER) != null) {
String username = session.getAttribute(CAS_FILTER_USER).toString();
//使用CAS使用者登入本地系統
loginToClientService(request,response,username);
return;
}
// otherwise, we need to authenticate via CAS
String ticket = request.getParameter("ticket");
// no ticket? abort request processing and redirect
if (ticket == null || ticket.equals("")) {
if (casLogin == null) {
throw new ServletException(
"When CASFilter protects pages that do not receive a 'ticket' "
+ "parameter, it needs a edu.yale.its.tp.cas.client.filter.loginUrl "
+ "filter parameter");
}
response.sendRedirect(
casLogin
+ "?service="
+ getService(request)
+ ((casRenew != null && !casRenew.equals(""))
? "&renew=" + casRenew
: ""));
return;
}
// Yay, ticket! Validate it.
String user = getAuthenticatedUser(request);
if (user == null)
throw new ServletException("Unexpected CAS authentication error");
// Store the authenticated user in the session
if (session != null) // probably unncessary
{
session.setAttribute(CAS_FILTER_USER, user);
//使用CAS使用者登入本地系統
loginToClientService(request,response,user);
}
}
// *********************************************************************
// Utility methods
/**
* 使用CAS伺服器驗證過的安全使用者名稱登入CAS 客戶端系統
* @param request
* @param response
* @param username 使用者名稱
* @throws IOException
* @throws ServletException
*/
private void loginToClientService(HttpServletRequest request,
HttpServletResponse response, String username)
throws IOException,ServletException{
/*
//判斷使用者在本地系統是否存在
if(username == null || username.equals("") || username.trim().length()==0){
response.sendRedirect(redirectURL);
}
else if (((TrustHandler)handler).findUserByName(request, username)){
//根據使用者名稱自動執行登入動作
((TrustHandler)handler).autoLoginWithUsername(request, response, username);
//登入成功後轉向工作桌面
request.getRequestDispatcher(desktopURL).forward(request,response);
}
else{
response.sendRedirect(redirectURL);
}*/
//HttpSession session = request.getSession();
TrustHandler tHandler = (TrustHandler)handler;
String fail = "errCode=";
int code = tHandler.loginWithUsername(request, response, username);
if (code == AuthCodeRepository.getSucCode()){
//登入成功後轉向工作桌面
String module = request.getQueryString();//取字尾引數
//response.sendRedirect("登入成功頁面(success)");
/*
if(session != null){
session.setAttribute("username", username);
}*/
//request.getRequestDispatcher(desktopURL).forward(request,response);
response.sendRedirect(desktopURL+"?"+module);
}else{
//登入失敗後根據錯誤編碼轉向錯誤頁面
fail += Integer.toString(code);
//response.sendRedirect("登入失敗頁面(fail)");
response.sendRedirect(redirectURL+"?"+fail);
}
}
/**
* Converts a ticket parameter to a username, taking into account an
* optionally configured trusted proxy in the tier immediately in front
* of us.
*/
private String getAuthenticatedUser(HttpServletRequest request)
throws ServletException {
ProxyTicketValidator pv = null;
//String SaxParserFactory = System.getProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
//String DocumentBuilderFactory = System.getProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
//String TransformaerFactory = System.getProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");
//System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
//System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
//System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");
try {
//System.out.println("CAS 開始驗證 ticket ==========================");
pv = new ProxyTicketValidator();
pv.setCasValidateUrl(casValidate);
pv.setServiceTicket(request.getParameter("ticket"));
pv.setService(getService(request));
pv.setRenew(Boolean.valueOf(casRenew).booleanValue());
pv.validate();
//System.out.println("CAS 驗證完畢 ticket ==========================");
if (!pv.isAuthenticationSuccesful())
throw new ServletException(
"CAS authentication error: " + pv.getErrorCode() + ": " + pv.getErrorMessage());
if (pv.getProxyList().size() != 0) {
// ticket was proxied
if (casAuthorizedProxy == null) {
throw new ServletException("this page does not accept proxied tickets");
} else {
boolean authorized = false;
String proxy = (String)pv.getProxyList().get(0);
StringTokenizer casProxies =
new StringTokenizer(casAuthorizedProxy);
while (casProxies.hasMoreTokens()) {
if (proxy.equals(casProxies.nextToken())) {
authorized = true;
break;
}
}
if (!authorized) {
throw new ServletException(
"unauthorized top-level proxy: '"
+ pv.getProxyList().get(0)
+ "'");
}
}
}
return pv.getUser();
} catch (SAXException ex) {
String xmlResponse = "";
if (pv != null)
xmlResponse = pv.getResponse();
throw new ServletException(ex + " " + xmlResponse);
} catch (ParserConfigurationException ex) {
throw new ServletException(ex);
} catch (IOException ex) {
throw new ServletException(ex);
}
}
/**
* Returns either the configured service or figures it out for the current
* request. The returned service is URL-encoded.
*/
private String getService(HttpServletRequest request)
throws ServletException {
// ensure we have a server name or service name
if (casServerName == null && casServiceUrl == null)
throw new ServletException(
"need one of the following configuration "
+ "parameters: edu.yale.its.tp.cas.client.filter.serviceUrl or "
+ "edu.yale.its.tp.cas.client.filter.serverName");
// use the given string if it's provided
if (casServiceUrl != null)
return URLEncoder.encode(casServiceUrl);
else
// otherwise, return our best guess at the service
return Util.getService(request, casServerName);
}
}
另外我們僅需要配置一個具有.loginWithUsername(request, response, username);函式的介面,及此Servlet的啟動相關引數就可以實現一個Servlet形式的登入入口,這樣我們在保留此應用原有登入入口的條件下可以增加CAS的SSO功能,不影響原有系統的使用,對原有系統也無需做過多的改動。
[@more@]來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/8700374/viewspace-1005583/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- CAS SSO單點登入客戶端環境搭建客戶端
- 3.CAS SSO單點登入客戶端環境搭建客戶端
- CAS SSO單點登入客戶端環境搭建之多租戶saas企業開發架構客戶端架構
- CAS SSO單點登入客戶端環境搭建之框架深度分析客戶端框架
- CAS SSO單點登入客戶端環境搭建之Spring Cloud + Spring Boot 企業架構客戶端CloudSpring Boot架構
- Spring Cloud + Spring Boot 企業架構之CAS SSO單點登入客戶端環境搭建CloudSpring Boot架構客戶端
- 關於CAS SSO單點登入客戶端環境搭建原始碼分析客戶端原始碼
- CAS SSO單點登入客戶端環境搭建解析之Spring Cloud + Spring Boot企業架構客戶端CloudSpring Boot架構
- Spring Cloud + Spring Boot + Mybatis 企業架構之CAS SSO單點登入客戶端環境搭建CloudSpring BootMyBatis架構客戶端
- 3.CAS SSO單點登入客戶端環境搭建&原始碼獲取客戶端原始碼
- spring系列—CAS客戶端與SpringSecurity整合Spring客戶端Gse
- SpringCloud大型企業分散式微服務雲架構原始碼+CAS SSO單點登入客戶端環境搭建SpringGCCloud分散式微服務架構原始碼客戶端
- vnc登入工具,好用的vnc登入工具,具體登入vnc客戶端使用教程VNC客戶端
- CAS SSO單點登入客戶端環境搭建之java版spring cloud 分散式微服務企業快速架構客戶端JavaSpringCloud分散式微服務架構
- Java版分散式微服務雲開發架構 Spring Cloud之CAS SSO單點登入客戶端環境搭建Java分散式微服務架構SpringCloud客戶端
- CAS SSO單點登入客戶端環境搭建之Java版微服務雲開發架構 Spring Cloud+Spring Boot客戶端Java微服務架構CloudSpring Boot
- SpringCloud分散式、微服務、雲架構快速開發平臺原始碼之CAS SSO單點登入客戶端環境搭建SpringGCCloud分散式微服務架構原始碼客戶端
- library官網登入入口,zlibrary中文網及客戶端/app客戶端APP
- Steam客戶端無法登入怎麼辦 新裝w10系統steam客戶端登不上去怎麼解決客戶端
- 客戶端登入Oracle 12.2伺服器報ORA-01017的解惑客戶端Oracle伺服器
- 避免 ChatGPT 電腦版客戶端彈出強制登入的方法ChatGPT客戶端
- CAS SSO單點登入服務端環境搭建服務端
- SourceTree 4.1.5中文破解免登入版(Git客戶端工具)Git客戶端
- CAS SSO單點登入服務端環境搭建之Spring Cloud Alibaba +多租戶saas企業開發架構服務端SpringCloud架構
- Spring Cloud企業架構之CAS SSO單點登入服務端環境搭建SpringCloud架構服務端
- Spring Cloud 企業架構之CAS SSO單點登入服務端環境搭建SpringCloud架構服務端
- Spring Cloud 企業架構之CAS SSO單點登入服務端環境搭建SpringCloud架構服務端
- Spring Cloud 企業架構之CAS SSO單點登入服務端環境搭建SpringCloud架構服務端
- 支付寶客戶端架構解析:iOS 客戶端啟動效能優化初探客戶端架構iOS優化
- CAS單點登入-簡介
- CAS單點登入-https配置HTTP
- 客戶端登陸logout操作,事務回滾客戶端Go
- PC客戶端Winform掃描微信二維碼登入網站Navite客戶端ORM網站Vite
- 2.基於CAS SSO單點登入服務端環境搭建架構原始碼服務端架構原始碼
- 2.基於CAS SSO單點登入服務端環境搭建+架構原始碼服務端架構原始碼
- CAS學習筆記三:SpringBoot自動配置與手動配置過濾器方式整合CAS客戶端筆記Spring Boot過濾器客戶端
- 支付寶客戶端架構解析:Android 客戶端啟動速度優化之「垃圾回收」客戶端架構Android優化
- CAS單點登入-基礎搭建
- win10 64位系統登入不了優酷客戶端如何解決Win10客戶端