CAS Authentication Using Perl

Overview

This document uses Perl to show how the basics of CAS work. If at all possible, it is best to use a supported CAS client, but if you cannot get one to work, the code below shows how basic CAS authentication works. Of course, you can do this in any programming language. 

Example Perl


sub GetUIDFromCAS {
   # Return the UID as obtained from CAS, either by validating an existing
   # ticket, or by referring the user to CAS for new ticket. In the latter
   case, the UID will be obtained by validating the ticket that is returned
   # here by CAS.
    
   use strict;
    
   use LWP::UserAgent;
   use CGI;
    
   my ($thisService,$casService) = @_;
    
   my $query = new CGI;
   my $ua = LWP::UserAgent->new;
    
   my $casGet;
   my $casTicket;
   my $response;
   my $uid;
    
   # Retrieve the CAS ticket, if any, from the incoming URI:
   $casTicket = $query->url_param('ticket');
    
   # If there is a ticket, validate it with CAS, returning the user's UID:
   if ($casTicket) {
      # Construct the full URL of the CAS validation service:
      $casGet =
         "$casService\/serviceValidate?ticket=$casTicket&service=$thisService";
      # Retrieve the validation output from CAS:
      $response = $ua->get($casGet);
      # Peel off the UID from the response:
      if ($response->content =~ /(\d+)<\/cas:user>/) {
         $uid = "$1";
         }
      # If there's no uid, then retrieve the entire response (which should
      # include an error message) and return that to the caller instead of
      # a uid.
      else {
         $uid = "casTicket: $casTicket; " . $response->content;
         }
      }
    
   # If a valid ticket was not part of the query string, redirect the user's
   # browser to CAS to get a fresh ticket:
   else {
      print
         $query->redirect(-location=>"$casService/login?service=$thisService");
      }
    
   # Return the UID (or else the error response) obtained from CAS:
   return $uid;
}