A Simple CAS Java Rest Client Example

Here are some notes from creating a simple Java Client to access a REST endpoint behind CAS authentication.

Resourcs for enabling CAS Rest Access:

And here is my simple implementation:

  • Main.java contains a runnable main method and makes the calls to our REST service
  • CasLogin.java holds our user’s credentials and makes the call to get the TicketGrantingTicket and the ServiceGrantingTicket.  You might be able to store the TGT in order to avoid passing the credentials over the wire for each request.
  • RestClient.java holds some helper methods to make http calls

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 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 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 should be false in our webapp’s spring security context (casContext.xml)
String postMessage = REST_BASE_URL + “/rest/api/v1/messages”;
Map params = new HashMap();
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 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 params) throws UnsupportedEncodingException {
StringBuilder postData = new StringBuilder();
for (Map.Entry 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”);
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *