java模拟登录CAS统一认证中心

java模拟登录CAS统一认证中心

cas版本:5.3.X

总的思路是:
1.先获取cas登录表单name为execution的参数值.
2.用account,password,execution发起httpPost请求,获取名为tgc的cookie写入response.
3.用account,password 发起httpPost请求,获取tgt.
4.用第3步获取的tgt获取serviceTicket.
5.response 302到 cas验证serviceTicket的地址,验证通过后自动返回项目主页.

废话不多说直接上代码.

所用到的url:

private static final String GET_EXECUTION = "https://www.cas-server.com:8443/cas/login?service=http%3A%2F%2Fwww.client.com%2Flogin%2Fcas&renew=true";
private static final String TAGET_URL = "http://www.client.com/login/cas";
private static final String GET_TOKEN_URL = "https://www.cas-server.com:8443/cas/v1/tickets";
private static final String GET_TOKEN_URL_TGC = "https://www.cas-server.com:8443/cas/login";

其中 www.cas-server.com:8443 是发布在tomcat里面使用8443端口的cas服务,www.client.com 是请求发起的客户端。

总的调用方法

	public void loginByAccount(final HttpServletRequest request,HttpServletResponse response) {
		try {
		    String account = "casAdmin";
			String password = "casAdmin";
			String execution = getExecution(GET_EXECUTION);
			putTGC(account, password, execution, response);
			String tgt = getTGT(account, password);
			if (StringUtils.isNotBlank(tgt)) {
				String ticket = getST(tgt,TAGET_URL);
				if(StringUtils.isNotBlank(ticket)){
					response.sendRedirect(TAGET_URL +"?ticket=" + ticket);
				}else{
					response.sendRedirect("/login");
				}
			} else {
				response.sendRedirect("/login");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("get tgc or tgt or st error" + e);
		}
	}

步骤1. getExecution(GET_EXECUTION);

public static String getLoginInfo(String GET_EXECUTION) {
		String execution = "";
		try {
			@SuppressWarnings({ "deprecation", "resource" })
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(GET_EXECUTION);
			HttpResponse response = client.execute(request);
			String strResult = EntityUtils.toString(response.getEntity());
			Page page = new Page();
			page.setRawText(strResult);
			page.setRequest(new Request(GET_EXECUTION));
			execution = page.getHtml().xpath("//input[@name='execution']/@value").get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return execution;
	}

步骤2. putTGC(account, password, execution, response);

public static void putTGC(String username, String password, String execution, HttpServletResponse responses)
			throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = null;
		try {
			CookieStore cookieStore = new BasicCookieStore();
			httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpPost httpPost = new HttpPost(GET_TOKEN_URL_TGC);
			List nvps = new ArrayList();
			nvps.add(new BasicNameValuePair("username", username));
			nvps.add(new BasicNameValuePair("password", password));
			nvps.add(new BasicNameValuePair("execution", execution));
			nvps.add(new BasicNameValuePair("_eventId", "submit"));
			nvps.add(new BasicNameValuePair("geolocation", ""));

			HttpEntity reqEntity = new UrlEncodedFormEntity(nvps, Consts.UTF_8);
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			httpPost.setEntity(reqEntity);

			CloseableHttpResponse response = httpClient.execute(httpPost);
			List cookies = cookieStore.getCookies();
			if (null != cookies && cookies.size() > 0) {
				javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(cookies.get(0).getName(),
						cookies.get(0).getValue());
				cookie.setPath(cookies.get(0).getPath());
				cookie.setHttpOnly(true);
				cookie.setSecure(true);
				cookie.setMaxAge(1800);
				responses.addCookie(cookie);
			}
		} finally {
			httpClient.close();
		}
	}

步骤3. getTGT(account, password);

public static String getTGT(String username, String password) throws ClientProtocolException, IOException {
		String tgt = "";
		CloseableHttpClient httpClient = null;
		try {
			CookieStore cookieStore = new BasicCookieStore();
			httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

			HttpPost httpPost = new HttpPost(GET_TOKEN_URL);
			List nvps = new ArrayList();
			nvps.add(new BasicNameValuePair("username", username));
			nvps.add(new BasicNameValuePair("password", password));

			HttpEntity reqEntity = new UrlEncodedFormEntity(nvps, Consts.UTF_8);
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			httpPost.setEntity(reqEntity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			try {

				Header[] tgtHead = response.getAllHeaders();
				if (tgtHead != null) {
					for (int i = 0; i < tgtHead.length; i++) {
						if (StringUtils.equals(tgtHead[i].getName(), "Location")) {
							tgt = tgtHead[i].getValue().substring(tgtHead[i].getValue().lastIndexOf("/") + 1);
						}
					}
				}
				HttpEntity respEntity = response.getEntity();
				EntityUtils.consume(respEntity);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				response.close();
			}
		} finally {
			httpClient.close();
		}
		return tgt;
	}

步骤4. getST(tgt,TAGET_URL);

public static String getST(String tgt,String TAGET_URL) {
		String serviceTicket = "";
		OutputStreamWriter out = null;
		BufferedWriter wirter = null;
		HttpsURLConnection conn = null;
		try {
			conn = (HttpsURLConnection) openConn(GET_TOKEN_URL + "/" + tgt);
			String param = "service=" + URLEncoder.encode(TAGET_URL, "utf-8");
			out = new OutputStreamWriter(conn.getOutputStream());
			wirter = new BufferedWriter(out);
			wirter.write(param);
			wirter.flush();
			wirter.close();
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			while ((line = in.readLine()) != null) {
				serviceTicket = line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return serviceTicket;
	}

步骤5. response.sendRedirect(TAGET_URL +"?ticket=" + ticket);
验证通过后cas会自动302回项目地址。

你可能感兴趣的:(java)