Legacy CAS2 Developer Documentation

This documentation is for the Web Login Service v2 (CAS2) that was retired end of calendar year 2014.
It is here for informational purposes only and is no longer applicable.

----------------------------------------------------------------------
File:   0-web-developers.txt
Descr:  Using CAS Web Login Service for Web site developers
By:     Russell Tokuyama
Date:   01/30/03
Mod:    $Id: 0-web-developers.txt 283 2009-09-30 20:55:13Z russ $
----------------------------------------------------------------------
CONTENTS
  1. CHANGE LOG
  2. OVERVIEW
  3. WEB LOGIN PROCESS
  4. URLs
  5. LOGIN SECURELY
  6. TOKEN VALIDATION
  7. LOGGING OUT
  8. SAMPLE WEB APP USING THE WEB LOGIN SERVICE
  9. FREQUENTLY ASKED QUESTIONS (FAQ)
     Q: Why does my site automatically login a returning user after they
        logout of their session with my site?
     Q: Is there a preferred method for logging out users?
 10. RESOURCES
----------------------------------------------------------------------
  1. CHANGE LOG
     01/30/2003; Initial version.  RT
     06/07/2011; Contact information and copyright dates updated. MH

  2. OVERVIEW
     The Web Login Service is available for only University of Hawaii
     (UH) Web site developers to use to authenticate users with their UH
     username and password.  This alleviates the problem of having to
     develop a user authentication system as part of the Web site
     development.  It also provides increased security for users by not
     allowing Web sites to handle their password (often done insecurely
     such as sending it in the clear).
     The Web Login Service does not provide authorization or access
     control services.  However, as a side effect of authenticating a
     user, a Web site (a.k.a., Web application) can get data about the
     user (person info) that can be used to perform access control.  If
     you do not perform any access control then anyone in the UH Core
     LDAP Directory Service will be able to use your Web site.  This is
     all current people in the UH System as well as visitors allowed by
     the Visitor Internet Access (VIA) at http://www.hawaii.edu/via/.
     
     The Web Login Service uses the CAS (Central Authentication Service)
     software written by Yale University (see RESOURCES below).  DO NOT
     contact Yale about this installation as the CAS software has been
     modified for UH-specific requirements.

  3. WEB LOGIN PROCESS
     When your Web site is set up to use the Web Login Service it uses a
     link on the login or main page of the site instead of an HTML form.
     The link redirects the user to the Web Login Service which presents
     them with a secure HTML form.  To be authenticated, the user only
     enters her UH username and password on the Web Login service's
     secure HTML form.
     After submitting her UH username and password the user is
     redirected back to your Web site.  Then, your Web site takes the
     authentication token that the Web Login Service sent along with the
     redirect and asks the Web Login Service to validate it.  If the
     user supplied the correct password the Web Login Service will
     return a confirmation message to your Web site.  Otherwise, a
     rejection message is returned.  The confirmation message will
     include the user's UH username, UH number (uhUuid), and full name
     (last, first middle initials).
     From this, the Web site will know who the user is.  The Web Login
     service does not provide session tracking information so it is your
     Web site's responsibility to handle session tracking.  Session
     tracking will reduce the number of round trips to the Web Login
     Service to validate the user each time a resource (URL/URI) is
     requested from your Web site.

  4. URLs
     a. Login securely
          https://login.its.hawaii.edu/cas/login
     b. Token validation
          https://login.its.hawaii.edu/cas/validate
     CAUTION: Use of any other URLs may cause problems.

  5. LOGIN SECURELY
     To have a user login securely put a link on your main page to the
     "login securely" URL with a request parameter named service and
     having a value that is the Service URL (i.e., the URL of the main
     page or a page that will be able to handle an HTTP request with a
     parameter).  This link should be labeled with something like "Login
     Securely" to establish in your user's mind that their password will
     not be seen by your application and is handled securely.  See the
     next section on token validation for information about how your
     application finds out their username.
     Here's an example:
       a. Service URL
          This is your site's menu page or the page after a user logs
          in.
       
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
https://myserver/myapp
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
       b. "Login Securely" link
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<A HREF=
"https://login.its.hawaii.edu/cas/login?service=https://myserver/myapp">
login securely</A>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     NOTES:
        1. The Service URL must be a real URL.  For example, most Web
           servers have a default page that is returned when you request
           a URL that ends with a forward slash character, "/".  This
           often results in redirects to index.html or index.htm while
           others use default.htm or default.asp.
        2. Since the Service URL is passed as the value of a query
           parameter, it should be URL-escaped to avoid being mangled by
           the Web Login Service.  Please refer to Appendix A of RFC
           2396 for details.
     
  6. TOKEN VALIDATION
     This section describes how your application finds out the username
     of the user that is logging in.
     When the Web Login Service has authenticated the user, it will
     redirect the user back to your Web site to the Service URL with an
     HTTP request parameter named, ticket, added on the end of the
     Service URL.  That Service URL can not be a static page since it
     won't be able to extract the authentication token and validate it.
     Here's an example of the URL used by the Web Login Service to
     redirect the request back to the Web site:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
https://myserver/myapp?ticket=ST-3-8tkkJbPThesE1cZjVVtc
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     The server-side processing of your Service URL must validate the
     extracted authentication token by sending an HTTP GET request
     with the following parameters:
       service=<Service URL>
       ticket=<authentication token>
     Here's an example of the request sent to the Web Login Service:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
https://login.its.hawaii.edu/cas/validate?service=https://myserver/myapp
&ticket=ST-95-a1kjb6g4Tcdeh17vfy6g
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NOTE: The request should be all on one line.
     After validating the authentication token, the Web Login Service
     will return a text document that is a message indicating success
     or failure of the user's authentication.
     The message sent back in response to a validation request is
     plain text.  If the authentication was successful, the message
     is:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
yes
teststaf
11668132
Staff M Teststaff
staff; student
uhm; kcc
eduPersonOrgDN=uhm,eduPersonAffiliation=staff; eduPersonOrgDN=kcc,eduPersonAffiliation=student
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     The message contains:
       a. Status of authentication
       b. UH username
       c. UH number (a.k.a., uhUuid - a UH unique identifier)
          NOTE: The UH number should be handled confidentially like a
                Social Security Number.  Especially with information
                about or associated with students.  FERPA laws
                constrain what may be published about students.  Please
                check with the Admissions and Records office about
                privacy about student information.
       d. Full name
       e. Affiliation - multiple affiliations are separated by
          semicolons.
       d. Campus - multiple campuses are separated by semicolons;
       f. Campus affiliation - multiple campus affiliations are separated by
                 semicolons.
     If the authentication step fails the user will remain at the Web
     Login Service's login page.  They would need to visit the Account
     Management page to reset their password or call the Help Desk for
     assistance.
     The authentication token is a one-time use token so any attempt
     to reuse it will result in this message being sent back:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
no
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     CAUTION:  After the Web Login Service redirects the user back to
     your app and you have validated the token, redirect the user to a
     URL that does not have the token in the URL.  Not doing so, opens
     the user to bookmarking a URL with a token in it.  This becomes a
     problem because the CAS software isn't on guard for this and this
     results in a looping problem sending the user back and forth
     between your site and the Web Login Service.

  7. LOGGING OUT
     Web applications that login a user handle their own session state
     and offer the user the ability to log out of a session.  However,
     upon returning to the Web application's Service URL, the user will
     be automatically logged back in because of the ticket-granting
     cookie if cookies are enabled in the user's browser.  This is a
     single sign-on feature across Web applications that use the Web
     Login Service.  There are two basic ways to "log out"; logout from
     application and Web Login Service single sign-on or logout from
     application and force re-authentication to the Web Login Service.
     To logout a user and prevent her from automatically logging back
     into a Web application, the Web application can forward the user to
     the Logout URL of the Web Login Service.  That URL will destroy the
     ticket-granting cookie that enables the single sign-on feature and
     gives the user a page that informs them that they have logged out of
     the Web Login Service.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
https://login.its.hawaii.edu/cas/logout
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     If you want a page from your site to be displayed to the user
     instead of the one from the Web Login Service, add the URL for that
     page as one of the parameters for the Logout URL.  The the user
     will see a page that is more closely associated with the Web
     application that they are logging out of.  In reality, the logout
     is from both the Web application and the single sign-on feature of
     the Web Login Service.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
https://login.its.hawaii.edu/cas/logout?service=https://myserver/myapp/
logout.html
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NOTE: The URL should be all on one line.
     If you want the user to authenticate every time they click on your
     login URL, change your login URL by appending "&renew=true".
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
https://login.its.hawaii.edu/cas/login?service=https://myserver/myapp
&renew=true
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NOTE: The URL should be all on one line.
     This will cause the Web Login Service to prompt the user to login
     whenever she clicks on the "Login securely" URL but still permits
     the user to single sign-on to other Web applications using the Web
     Login Service.

     NOTE: Since the Service URL is passed as the value of a query
           parameter, it should be URL-escaped to avoid being mangled by
           the Web Login Service.  Please refer to Appendix A of RFC
           2396 for details.
  8. ACCESS CONTROL
     It is every developer's responsibility to perform access control
     (authorization) after a user has logged on to their Web site.  This
     is done by checking the person info.  The affiliation, campus, or
     campus affiliation data should be enough to filter out unauthorized
     users.  Alternatively, you explicitly allow or disallow by
     username.  In any event, the developer must make this decision.
  9. SAMPLE WEB APPS USING THE WEB LOGIN SERVICE
     a. Here's an ASP file that prints out the user's name after they
        have authenticated.  Once successfully authenticated, the ASP
        page remembers the user's name and username.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<%@ Language=JScript %>
<%
// File: default.asp
// Mod:  02/06/03, Russell Tokuyama (UH ITS); set up for UH.
//
// Install in Inetpub\wwwroot\HelloCas and request:
//   http://myserver/HelloCas/
//
// Based on sample ASP code that uses CAS by Howard Gilbert.
//
// If you logon, it says "Hello " followed by your userid
// For the Web server to talk to the CAS server, this code depends on the
// Microsoft ServerXMLHTTP control provided with MSXML. If the MS XML
// parser is not already installed on the IIS host machine, 
// download version 3.0 SP1 or better from http://www.microsoft.com/xml
// Insert name of CAS Server at your location
var CAS_Server = "https://login.its.hawaii.edu/cas/";
// Note: Request.ServerVariables("SERVER_NAME") or anything based on
// the HTTP "Host" header should NOT be used; this header is supplied by
// the client and isn't trusted. (--SB)
// Insert public name of IIS Server hosting this script
var MyServer = "http://buzz1.its.hawaii.edu:8008/";
var greeting = "World"; // In case I fail
var line0 = "";
var line1 = "";
var line2 = "";
var line3 = "";
var line4 = "";
// See if already logged on
var uid = Session.Contents("Netid");
if (!uid) {
    // Check for ticket returned by CAS redirect
    var ticket = Request.QueryString.Item("ticket").Item;
    if (!ticket) {
        // No session, no ticket, Redirect to CAS Logon page
        var url = CAS_Server+"login?"+
                  "service="+MyServer+"HelloCas/default.asp"
        Response.Redirect(url);
        Response.End;   
    } else {        
        // Back from CAS, validate ticket and get userid
        var http = Server.CreateObject("MSXML2.ServerXMLHTTP");
        var url = CAS_Server+"validate?ticket="+ticket+"&"+
                  "service="+MyServer+"HelloCas/default.asp";
        http.open("GET",url,false); // HTTP transaction to CAS server
        http.send();
                
        var resp=http.responseText.split('\n'); // Lines become array members
        if (resp[0]=="yes") {  // Logon successful
            greeting = resp[1]; // get userid for message
            line0 = resp[0] + "\n";
            line1 = resp[1] + "\n";
            line2 = resp[2] + "\n";
            line3 = resp[3] + "\n";
            line4 = resp[4] + "\n";
            // Save for subsequent calls
            Session.Contents("Netid")=resp[1];
            Session.Contents("Name")=resp[3];
        }
    }
}
else {
    greeting = Session.Contents("Name");
}
%>
<HTML>
<HEAD><title>CAS ASP Example application</title></HEAD>
<BODY>
<P>Hello <%=greeting%> (<%=uid%>)
</P>
<P>The validation message contains:<BR>
<PRE>
<%=line0%>
<%=line1%>
<%=line2%>
<%=line3%>
<%=line4%>
</PRE>
</BODY>
</HTML>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     b. Here's a PHP script that counts the number of times a user
        visits the URL.  The user's person info is also displayed.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<?php
    // cas-demo.php - Demo of PHP using the Web Login Service
    //              - 06/08/07, Russell Tokuyama
    //              - Copyright (c) University of Hawaii 2007
    //                See the end of this file for the copyright notice.
    //
    //-------------------------------------------------------------
    //
    // The only things that need to be configured:
    //
    //-------------------------------------------------------------
    // 1. Set this to the URL of this script.
    $me = "http://somehost/cas-demo.php";
    // 2. Set this to the base URL of the Web Login Service (no trailing 
    //    slash).
    $weblogin = "https://login.its.hawaii.edu/cas";
    //-------------------------------------------------------------
    //
    // These are based on the above variables.
    //
    // Login link to the Web Login Service
    $login = "${weblogin}/login?service=" . urlencode($me);
    // Logout link to the Web Login Service
    $logout = "${weblogin}/logout?service=" . urlencode($me) .
              urlencode("?logoff=yes");
    //-------------------------------------------------------------
    //
    // For help with problems, look in your Apache web server's error_log
    // file.
    //
    //-------------------------------------------------------------

    //-------------------------------------------------------------
    // This function will call the Web Login Service's validate URL on
    // the service ticket returned when a user logins there.  It returns
    // the elements of the validation response.  See the Web Login
    // Service documentation at
    // http://www.hawaii.edu/infotech/middleware/weblogin/.
    //-------------------------------------------------------------
    function validate($svc, $tkt) {
        global $weblogin;
        // validation URL of the Web Login Service
        $validate_url = "$weblogin/validate" .
                        '?service=' . urlencode($svc) .
                        '&ticket=' . urlencode($tkt);
        // Call the validation service
        error_log('validate(): validating [' . $validate_url . ']');
        $resp = file_get_contents($validate_url );
        if (empty($resp)) {
            error_log('validate(): empty response');
        }
        else {
            // Parse the validation response to get the username and
            // person info for the authenticated user.
            list($status, $uid, $uhuuid, $name, $affil) = explode("\n", $resp);
            if (empty($status)) {
                error_log('validate(): response didn\'t explode');
            }
            return array($status, $uid, $uhuuid, $name, $affil);
        }
        return;
    }

    //-------------------------------------------------------------
    // This part of the script handles calling the Web Login Service
    // to authenticate the user if the user doesn't have a session yet,
    // validating the service ticket after they are authenticated, and
    // handling the user's session which is independent of the
    // authentication with the Web Login Service.
    //-------------------------------------------------------------
    session_start();
    if ($_GET['logoff']) {
        session_destroy();
        header("Location: $me");
        exit;
    }
    if (!session_is_registered('name')) { // not logged in
        $ticket = $_GET['ticket'];
        if (! empty($ticket)) {
            // validate service ticket
            list ($status, $uid, $uhuuid, $name, $affs) =
                validate($me, $ticket);
            if ($status == 'yes') {
                // save data in session
                $_SESSION['name']   = "$name";
                $_SESSION['uid']    = "$uid";
                $_SESSION['affs']   = "$affs";
                $_SESSION['count']  = 1;
                $name = "$name";
                // Get rid of the query parameters in the URL.
                header("Location: $me");  // redirect to me
                exit;
            } else {
                if (empty($status)) {
                    error_log('status is empty');
                    $action = 'network_error';
                }
                else {
                    error_log('status: ' . $status);
                    // tried to reuse the service ticket
                    $action = 'reuse_error';
                    session_destroy();
                }
            }
        }
        else {
            error_log('ticket is empty');
            $action = 'empty_ticket';
        }
    } else {  // previously logged in
        $action = 'continue';
        // get data from session
        $name   = $_SESSION['name'];
        $uid    = $_SESSION['uid'];
        $affs   = $_SESSION['affs'];
        $count  = $_SESSION['count'];
        // bump our counter
        $_SESSION['count']++;
    }
    //-------------------------------------------------------------
    // The HTML portion follows.
    //-------------------------------------------------------------
?>
<html>
  <head>
    <title>Demo of Web Login Service Using PHP</title>
  </head>
  <body>
    <h1>My App</h1>
<?php
    if ($action == 'continue') {
        if ($count == 1) {
?>
     <p>Welcome, <?php echo "$name"; ?>!</p>
<?php
        }
        else {
?>
     <p>Welcome back, <?php echo "$name"; ?>!</p>
<?php
        }
?>
     <p>We know this about you:</p>
     <ul>
       <li>UH username = <?php echo "$uid"; ?><li>
       <li>UH affiliation = <?php echo "$affs"; ?><li>
     </ul>
     <p>This is your <?php echo "$count"; ?> time here.</p>
     <p><a href="<?php echo "$me" ?>">Continue</a></p>
     <p><a href="<?php echo "$me?logoff=yes" ?>">log off (clear session)</a></p>
     <p><a href="<?php echo "$logout" ?>">log off (no more single-signon)</a></p>
<?php
    }
    else {
        if ($action == 'reuse_error') {
?>
     <p>Can't reuse service tickets!</p>
<?php
        }
        else {
?>
     <p><?php echo "Action: $action" ?></p>
<?php
        }
?>
     <p>Please <a href="<?php echo "$login"; ?>">login securely</a> by clicking on the link.</p>
<?php
    }
?>
    </body>
</html>
<?php
    //-------------------------------------------------------------
    // Copyright (c) 2011 University of Hawaii.  All rights reserved.
    //
    // Redistribution and use in source and binary forms, with or without
    // modification, are permitted provided that the following conditions
    // are met:
    //
    // 1. Redistributions of source code must retain the above copyright
    //    notice, this list of conditions and the following disclaimer.
    //
    // 2. Redistributions in binary form must reproduce the above copyright
    //    notice, this list of conditions and the following disclaimer in
    //    the documentation and/or other materials provided with the
    //    distribution.
    //
    // 3. Redistributions of any form whatsoever must retain the following
    //    acknowledgment:
    //    "This product includes software developed by the University of
    //    Hawaii (http://www.hawaii.edu/)."
    //
    // THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF HAWAII "AS IS" AND ANY
    // EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    // PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE UNIVERSITY OF HAWAII
    // OR THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    // OF THE POSSIBILITY OF SUCH DAMAGE.
    //-------------------------------------------------------------
?>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     c. An alternative method of using the Web Login Service with PHP is
        available at:
          http://www.hawaii.edu/infotech/webservice/cas.html
        This is some information put together by DLUS for ITS hosted web
        sites and uses PHP's interface to the cURL library.
     d. Here's a JSP demo.  It comes in two JSPs: cas-demo.jsp and the
        supporting cas-handler.jsp.  You'll also need the Java CAS
        client jar which you can get from:
        http://www.ja-sig.org/products/cas/client/javaclient/index.html
        which has a link to casclient-2.1.1.jar.  Install the
        casclient-2.1.1.jar file in your web app's WEB-INF/lib
        directory.  Install the JSP files in your web app's main
        directory.  Point your browser at cas-demo.jsp.
        
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<%
// cas-demo.jsp - Demo of using the Web Login Service with JSPs
//              - 08/21/08, russ@hawaii.edu
//              - Copyright (c) University of Hawaii 2011
//                All rights reserved.
//              - See the end of this file for the LICENSE
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
  <title>Demo of Sessions Using JSP</title>
</head>

<body>
  <h1>Web Login Demo Client Application</h1>
  <%@ include file="cas-handler.jsp" %>
  <%
  //  For this demo, we are the front page and inside  protected page.
  //  The service URL is the inside page but URL-encoded.
  String frontPage  = request.getRequestURL().toString();
  String insidePage = request.getRequestURL().toString();
  String serviceURL = URLEncoder.encode(insidePage);
  String weblogin   = "https://russ.mgt.hawaii.edu:8443/cas";
  String netId = doWebLogin(request, response, weblogin, frontPage, serviceURL);
  // handle other actions like logging off
  String logoff = request.getParameter("logoff");
  if (logoff != null) {
      logIt("logging off and invalidating session");
      session.invalidate();
      response.sendRedirect(frontPage);
      return;  // bail here or get weird results
  }
  // The main part: show the front page or the inside protected page.
  if (netId == null) { // not logged in --> the outside page
      // show login link
      String loginLink   = weblogin + "/login?service=" + serviceURL;
      logIt("setting loginLink to = " + loginLink);
      logIt("not logged in yet; showing welcome page");
  %>
      <p> Welcome! </p>
      <p>Please <a href="<%= loginLink %>">login securely</a> by clicking
          on the link.</p>
  <%
  }
  else {  // logged in --> the inside protected page
      // show the number of times the user visited me
      Integer visits = (Integer) session.getAttribute("visits");
      if (visits == null) {
          visits = new Integer(1);
          logIt("first visit");
      }
      else {
          visits = new Integer(visits.intValue() + 1);
          logIt("bumped visits to " + visits);
      }
      session.setAttribute("visits", visits);
  %>
      <p> Welcome, <%= netId %> </p>
      <p> Number of visits = <%= visits.toString() %></p>
      <p><a href="<%= frontPage %>"> do it again </a></p>
      <p><a href="<%= frontPage + "?logoff" %>">log off (clear session)</a></p>
  <%
  } // else {  // logged in --> the inside protected page
  %>
  <p>
  <%= (new java.util.Date()).toLocaleString() %>
  </p>
  </body>
</html>
<%
// University of Hawaii LICENSE
//--------------------------------------------------------------------
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materials provided with the
//    distribution.
//
// 3. Redistributions of any form whatsoever must retain the following
//    acknowledgment:
//    "This product includes software developed by the University of
//    Hawaii (http://www.hawaii.edu/)."
//
// THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF HAWAII "AS IS" AND ANY
// EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE UNIVERSITY OF HAWAII
// OR THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//--------------------------------------------------------------------
%>
<%
// cas-handler.jsp - functions for using the CAS Client library to login
//                   users via the Web Login Service.
//                 - 08/21/08, russ@hawaii.edu
//                 - Copyright (c) University of Hawaii 2008
//                   All rights reserved.
//                 - See the end of this file for the LICENSE
//
//--------------------------------------------------------------------
//  Usage:
//    1. Include this file in your front page JSP.
//    2. Set up these URLS:
//       a. Front page - the advertised to users and they bookmark.
//       b. Inside page - where the application does all the work.
//       c. Service URL - the URL-encode form of the inside page.
//       d. Web Login Service - the one that authenticates users; not us.
//    3. Call the doWebLogin() method to get the netId (a.k.a., username)
//       of the user.  The Web Login Service is the only one to handle
//       the user's credentials.  We'll end with the netId if they
//       authenticate successfully with the Web Login Service.
//
//   Example JSP code:
//
//  String front    = request.getRequestURL().toString();
//  String inside   = request.getRequestURL().toString();
//  String service  = URLEncoder.encode(insidePage);
//  String weblogin = "https://russ.mgt.hawaii.edu:8443/cas";
//
//  String netId = doWebLogin(request, response, weblogin, front, service);
//
//--------------------------------------------------------------------
%>
<%@ page import="edu.yale.its.tp.cas.client.ServiceTicketValidator" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.io.IOException" %>
<%@ page import="org.xml.sax.SAXException" %>
<%@ page import="javax.xml.parsers.ParserConfigurationException" %>
<%!
// A crude logging method - entry is sent to stderr.
protected void logIt(String msg) {
    String ts = (new java.util.Date()).toLocaleString();
    System.err.println(ts + " " + msg);
}
// Return a netId (a.k.a., username); null if not logged in or
// can't validate the service ticket from the Web Login Service.
protected String doWebLogin(HttpServletRequest req,
                            HttpServletResponse res,
                            String weblogin,
                            String frontPage,
                            String serviceURL) 
throws IOException, SAXException, ParserConfigurationException {
    String validateURL = weblogin + "/serviceValidate";
    HttpSession sess = req.getSession();
    String sessionId = sess.getId();
    logIt("sessionId = " + sessionId);
    String netId = (String) sess.getAttribute("netId");
    logIt("netId from session = " + netId);
    // if there's a service ticket, try to validate it
    String ticket = req.getParameter("ticket");
    logIt("got a ticket: " + ticket);
    if (ticket != null) {
        ServiceTicketValidator validator = new ServiceTicketValidator();
        validator.setCasValidateUrl(validateURL);
        validator.setService(serviceURL);
        validator.setServiceTicket(ticket);
        validator.validate();
        logIt("validation returned: " + validator.getResponse());
        if (validator.isAuthenticationSuccesful()) {
            netId = validator.getUser();
            logIt("authN successful for " + netId);
            // remember the user's username
            sess.setAttribute("netId", netId);
            // redirect back to me to get rid of the ticket in URL
            logIt("redirecting back to " + frontPage);
            res.sendRedirect(frontPage);
            return null;
        }
    }
    return netId;
}
%>
<%
// University of Hawaii LICENSE
//--------------------------------------------------------------------
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materials provided with the
//    distribution.
//
// 3. Redistributions of any form whatsoever must retain the following
//    acknowledgment:
//    "This product includes software developed by the University of
//    Hawaii (http://www.hawaii.edu/)."
//
// THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF HAWAII "AS IS" AND ANY
// EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE UNIVERSITY OF HAWAII
// OR THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//--------------------------------------------------------------------
%>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 10. FREQUENTLY ASKED QUESTIONS (FAQ)
     Q: Why does my site automatically login a returning user after they
        logout of their session with my site?
     A: The Web Login Service provides a single sign-on mechanism by
        default.  This is a convenience for the user visiting sites that
        use the Web Login Service.  If you want you make sure your users
        always authenticate themselves to the Web Login Service before
        entering your site, you need to add the renew parameter to your
        login redirect URL.

     Q: Is there a preferred method for logging out users?
     A: Which to use is a judgement call for Web apps.  When in doubt,
        use the Logout URL.  It will always force a user to
        re-authenticate to the Web Login Service.  Not having single
        sign-on is not necessarily a bad thing.
        The general user finds it difficult to understand the security
        implications of the various shades (actually, only two) of
        logging out.  If an app might be used from a kiosk (public use
        PC and browser) it is safer to set things up to logout
        completely using the Logout URL.
        A future enhancement could make single sign-on an option for the
        user so the default will be no single sign-on.  If the user
        chooses to enable single sign-on when authenticating to the Web
        Login Service, only those apps that don't use the renew
        parameter will permit single sign-on if the user doesn't logout
        via the Logout URL from a previously visited app.
     Q: Can anyone use my Web site?
     A: Anyone that is in the UH Core LDAP Directory Service.  In other
        words, current people in the UH System (ten campuses, system
        offices, some RCUH employees) and visitors (temporary guest
        accounts) managed by VIA (www.hawaii.edu/via/).  See section 8
        above.
 11. RESOURCES
     a. If you have questions, contact the ITS IAM Group at 
        its-iam-help@lists.hawaii.edu.  Be sure to provide details.  
        Assistance is only provided to the UH community.
     b. Yale University's Central Authentication Service (CAS)
        URL: http://www.yale.edu/tp/cas/
        NOTE: DO NOT contact Yale University's about Technology and
              Planning department about this installation as the CAS
              software has been modified for UH-specific requirements.
        More recently, CAS became a part of JA-SIG.
        URL:  http://www.ja-sig.org/products/cas/

----------------------------------------------------------------------
vim:ai expandtab tw=72