Skip to content

CAS Restful Java Client

October 27, 2009
tags: ,

Here is a sample test cas restful java client.
To validate the service ticket you can use the code that is similar to yale cas client SecureUtil.java class sending an https request to /serviceValidate URL of CAS.

The below code is an older version. Uploaded a working copy of the code here:

http://snippets.dzone.com/posts/show/9341

public static boolean validateFromCAS(String username, String password) throws Exception
	{

		String url = "https://myPC.com:8443/cas/v1/tickets";
		try
		{
			HttpsURLConnection hsu = (HttpsURLConnection)openConn(url);
			String s =   URLEncoder.encode("username","UTF-8") + "=" + URLEncoder.encode("adriza","UTF-8");
			s+="&" +URLEncoder.encode("password","UTF-8") + "=" + URLEncoder.encode("adriza","UTF-8");

			System.out.println(s);
			OutputStreamWriter out = new OutputStreamWriter(hsu.getOutputStream());
			BufferedWriter bwr = new BufferedWriter(out);
			bwr.write(s);
			bwr.flush();

			String tgt = hsu.getHeaderField("location");
			System.out.println( hsu.getResponseCode());
			if(tgt != null && hsu.getResponseCode() != 400)
			{
				System.out.println(tgt);

				System.out.println("Tgt is : " + tgt.substring( tgt.lastIndexOf("/") +1));
				tgt = tgt.substring( tgt.lastIndexOf("/") +1);
		        bwr.close();
		        closeConn(hsu);

		        String serviceURL = "http://myPC.com:8080/testingWebSvc";
		        s = URLEncoder.encode("service","utf-8") +"=" + URLEncoder.encode(serviceURL,"utf-8");
		        hsu = (HttpsURLConnection)openConn(url+ "/"+ tgt);
		        System.out.println("Response code is:  " + hsu.getResponseCode());

     	                BufferedReader isr = new BufferedReader(   new
                                    InputStreamReader(hsu.getInputStream()));
		        String line;
		        System.out.println( hsu.getResponseCode());
		        while ((line = isr.readLine()) != null) {
		        	System.out.println( line);
		        }
		        isr.close();
		        hsu.disconnect();
		        return true;
		    }
			else
			{
				return false;
			}
		}
		catch(MalformedURLException mue)
		{
			mue.printStackTrace();
			throw mue;
		}
		catch(IOException ioe)
		{
			ioe.printStackTrace();
			throw ioe;
		}
	}
Advertisements
2 Comments leave one →
  1. Anonymous permalink
    December 9, 2009 4:43 am

    Can you paste full source code.

    Thanks,
    R

  2. techzen permalink*
    December 16, 2009 5:00 pm

    The dzone link is provided.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: