最近项目中遇到CAS授权的系统,客户端需要调用https接口获取数据,下面给出具体怎么通过CAS授权的代码示例。
public class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
private static String doCasLoginRequest(DefaultHttpClient httpclient, String url) throws IOException {
try {
String result = "";
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String tempLine = rd.readLine();
String s = "<input type=\"hidden\" name=\"lt\" value=\"";
while (tempLine != null) {
int index = tempLine.indexOf(s);
if (index != -1) {
String s1 = tempLine.substring(index + s.length());
int index1 = s1.indexOf("\"");
if (index1 != -1)
result = s1.substring(0, index1);
}
tempLine = rd.readLine();
}
if (entity != null) {
entity.getContent().close();
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static DefaultHttpClient casLogin(String url) throws Exception {
DefaultHttpClient httpClient = new SSLClient();
httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0");
HttpPost post = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "admin"));
nvps.add(new BasicNameValuePair("password", "xxxx"));
nvps.add(new BasicNameValuePair("lt", doCasLoginRequest(httpClient, url)));
nvps.add(new BasicNameValuePair("execution", "e1s1"));
nvps.add(new BasicNameValuePair("_eventId", "submit"));
nvps.add(new BasicNameValuePair("submit", "登录"));
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
httpClient.getCookieStore().getCookies().forEach(c -> {
System.out.println(c.getName() + "=>" + c.getValue());
});
entity.getContent().close();
}
return httpClient;
}
执行过程中可以发现,控制台如果能正常打印出cookie中的seesionID等授权信息,就说明通过cas认证了,这个时候,用这个
httpclient就可以进行各种post/get请求了。
本文介绍了一种使用Java实现的CAS认证系统案例。该系统通过自定义的SSL客户端处理HTTPS请求,并详细展示了如何通过POST请求完成CAS认证流程,包括获取会话ID等关键步骤。
2448

被折叠的 条评论
为什么被折叠?



