Skip to content

Instantly share code, notes, and snippets.

@bmchild
Created May 2, 2014 22:08
Show Gist options
  • Save bmchild/cacbf6a560af5a99a501 to your computer and use it in GitHub Desktop.
Save bmchild/cacbf6a560af5a99a501 to your computer and use it in GitHub Desktop.
Simple CAS Java Rest Client
package com.bmchild.pocrestclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.security.sasl.AuthenticationException;
public class CasLogin {
private static final Logger LOGGER = Logger.getLogger(CasLogin.class.getName());
private String username;
private String password;
private String casUrl;
private RestClient restClient;
public CasLogin(String username, String password, String casUrl) {
this.username = username;
this.password = password;
this.casUrl = casUrl;
restClient = new RestClient();
}
public String getServiceTicket(String serviceUrl) throws IOException {
// get TGT
String location = getTicketGrantingTicket(username, password);
// get SGT
return getServiceGrantingTicket(location, serviceUrl);
}
/**
* With the TGT location and service url this will get the SGT
* @param tgtLocation
* @param serviceUrl
* @return
* @throws IOException
*/
private String getServiceGrantingTicket(String tgtLocation, String serviceUrl) throws IOException {
Map<String,Object> params = new LinkedHashMap<>();
params.put("service", serviceUrl);
params.put("method", "POST");
HttpURLConnection conn = restClient.post(tgtLocation, params);
StringBuilder responseBuilder = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String input;
while ((input = in.readLine()) != null) {
responseBuilder.append(input);
}
in.close();
String response = responseBuilder.toString();
LOGGER.info("SGT -> " + response);
return response;
}
/**
* Gets the TGT for the given username and password
* @param username
* @param password
* @return
* @throws IOException
*/
private String getTicketGrantingTicket(String username, String password) throws IOException {
Map<String,Object> params = new LinkedHashMap<>();
params.put("username", username);
params.put("password", password);
HttpURLConnection conn = restClient.post(casUrl, params);
if(conn.getResponseCode() == 400) {
throw new AuthenticationException("bad username or password");
}
String location = conn.getHeaderField("Location");
LOGGER.info("TGT LOCATION -> " + location);
return location;
}
}
package com.bmchild.pocrestclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
public class Main {
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
private static final String CAS_URL = "https://casserver.com/sso/v1/tickets";
private static final String REST_BASE_URL = "http://restservice.com";
public static void main(String[] args) throws IOException {
CasLogin casLogin = new CasLogin("user", "pass", CAS_URL);
RestClient client = new RestClient();
/* example GET */
Main main = new Main();
String getSimple = REST_BASE_URL + "/rest/api/v1/messages";
main.printContent( client.get(getSimple + "?ticket=" + casLogin.getServiceTicket(getSimple)) );
String getParams = REST_BASE_URL + "/rest/api/v1/messages?page=1";
main.printContent( client.get(getParams + "&ticket=" + casLogin.getServiceTicket(getParams)));
String getSimple2 = REST_BASE_URL + "/rest/api/v1/messages/4405078";
main.printContent( client.get(getSimple2 + "?ticket=" + casLogin.getServiceTicket(getSimple2)));
/* Example POST */
// see https://groups.google.com/forum/#!searchin/jasig-cas-user/post$20to$20rest$20resource/jasig-cas-user/NWmFahj9usk/YBECPJULN3sJ
// looks like <property name="redirectAfterValidation" value="true" /> should be false in our webapp's spring security context (casContext.xml)
String postMessage = REST_BASE_URL + "/rest/api/v1/messages";
Map<String, Object> params = new HashMap<String, Object>();
params.put("body", "message body");
params.put("toAddress", "11220"); // from address lookup
params.put("subject", "message subject");
main.printContent( client.post(postMessage + "?ticket=" + casLogin.getServiceTicket(postMessage), params));
}
private void printContent(HttpURLConnection con) {
if (con != null) {
try {
LOGGER.info("Response Code -> " + con.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input;
StringBuilder content = new StringBuilder();
while ((input = br.readLine()) != null) {
content.append(input);
}
br.close();
LOGGER.info("Content -> " + content.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.bmchild.pocrestclient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.logging.Logger;
public class RestClient {
private static final Logger LOGGER = Logger.getLogger(RestClient.class.getName());
public URL createUrl(String url) throws MalformedURLException {
return new URL(url);
}
public HttpURLConnection get(String url) throws IOException {
LOGGER.info("Getting from url '" + url +"'");
URL connectionUrl = createUrl(url);
return (HttpURLConnection) connectionUrl.openConnection();
}
/**
* Helper Method to post data to the given url and with the given params
* @param url
* @param params
* @return
* @throws IOException
*/
public HttpURLConnection post(String url, Map<String, Object> params) throws IOException {
LOGGER.info("Posting to url '" + url +"' w/ params '" + params.toString() + "'");
URL connectionUrl = createUrl(url);
byte[] postDataBytes = convertParamMapToBytes(params);
HttpURLConnection conn = (HttpURLConnection)connectionUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
return conn;
}
/**
* Helper method to convert a map to POST bytes
* @param params
* @return
* @throws UnsupportedEncodingException
*/
private byte[] convertParamMapToBytes(Map<String, Object> params) throws UnsupportedEncodingException {
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
return postData.toString().getBytes("UTF-8");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment