Skip to main content

CAS Single Sign-On Integration

The Concept

In this post I'll explain how to integrate CAS (Central Authentication Service) with Tridion Content Manager. This is a back-end integration, which will allow users with a CAS login access Tridion Content Manager GUI and other back-end modules (e.g. Template Builder, Content Porter, etc) using their CAS login.

Explaining the inner workings of CAS is not in the scope of this post (have a look at this wiki for more information). Also a familiarity with Tridion SSO is recommended, but not necessary. I think the documentation does a good job explaining the basics of SSO and Tridion and how to enable/configure it. Check it out on here (login required).

In a nutshell, this is how single sign-on works with Tridion back-end:
  1. SSO software authenticates a user and places the login and user name in a request header that is forwarded to Tridion;
  2. Tridion GUI (the web application) reads this user name and login and authorizes the user against the Tridion users in the Content Manager;
CAS single sign-on does not place such a header in the request, so here we have to intervene and code a little .net HTTP Module that does just that. We then specify the HTTP Module in the web.config files on Tridion CM.

The Code

Class CASAuthenticator

I implemented the IHttpModule interface in a class called CASAuthenticator. This is my custom module I will use for checking whether we have a CAS ticket and if not, redirect the request to CAS for authentication. Once a ticket is obtained, the ticket ID is saved in a cookie on the visitor's browser (see details below). The ticket ID is validated and from it, if successful, CAS gives us the NET ID -- the user login. This login is placed further into the request as a header and the request continues to hit the Tridion web-application.

public class CASAuthenticator : IHttpModule
{
    public const string CASHOST = "https://secure.its.yale.edu/cas/";
    public const string COOKIE_NAME = "casauth";
    public const string HEADER_NAME = "netid";
    public readonly int SESSION_EXPIRATION = 30; // minutes

    private const string TICKET_PARAM = "ticket";
    private ICacheWrapper cache;
...

I used a simple web cache in the form of a HttpRuntime.Cache to store the tickets and their internal state.

Method BeginRequest

This method is hooked to the application.BeginRequest event. This ensures it is executed with every request. The logic is pretty simple -- first it attempts to read a Ticket object from the request (see details below). Upon validation it either sets the request header or forces a login via CAS.

private void BeginRequest(object sender, EventArgs e)
{
    HttpApplication application = (HttpApplication)sender;
    HttpRequest request = application.Request;
    HttpResponse response = application.Response;
    LOG.Debug("Begin request " + request.Url);

    CASTicket ticket = GetTicket(request, response);
    if (ticket.Validate(request, response))
    {
        LOG.Debug("Setting header " + HEADER_NAME + " = " + ticket.NetId);
        request.Headers[HEADER_NAME] = ticket.NetId;
    }
    else
    {
        EnforceLogin(request, response);
    }
}

Method GetTicket

Most of the module's logic is in this method. The check is made on a ticket request parameter. On a first request such a parameter is empty, so we then check whether a cookie is present with given name. Again, on a first request there would be no such cookie, so a CAS login is forced (details about that below).

Once CAS authenticates the request, it forwards the request back to the original URL and it adds a request parameter 'ticket' having the value of the CAS session/ticket ID. On this subsequent request, the method GetTicket would extract the ticket ID and a) set a cookie with the ticket ID and b) place the ticket ID in a cached object CASTicket, which is then also returned.

private CASTicket GetTicket(HttpRequest request, HttpResponse response)
{
    CASTicket casTicket;
    string ticketId = request.QueryString[TICKET_PARAM];

    if (string.IsNullOrEmpty(ticketId))
    {
        HttpCookie cookie = request.Cookies[COOKIE_NAME];
        if (cookie == null)
        {
            EnforceLogin(request, response);
            return null;
        }
        else
        {
            string key = cookie.Value;
            if (!cache.TryGet(key, out casTicket))
            {
                EnforceLogin(request, response);
                return null;
            }
        }
    }
    else
    {
        string key = Utils.MD5(ticketId).ToString("n");
        response.Cookies.Add(new HttpCookie(COOKIE_NAME, key));

        casTicket = new CASTicket(ticketId);
        cache.Insert(key, casTicket, SESSION_EXPIRATION);

        string url = request.Url.AbsolutePath;
        url += Utils.RemoveQueryString(request.QueryString, new string[] { TICKET_PARAM });
        response.Redirect(url);
        return null;
    }

    return casTicket;
}

Method EnforceLogin

This method simply redirects the request to the CAS authentication URL. At the same time it passes a 'service' URL parameter indicating the current URL or the URL to return to upon a successful login.

private void EnforceLogin(HttpRequest request, HttpResponse response)
{
    string service = request.Url.GetLeftPart(UriPartial.Path);
    string redir = CASHOST + "login?" + "service=" + HttpUtility.UrlEncode(service);
    response.Redirect(redir);
}

Method Validate on class CASTicket

Class CASTicket is a simple bean, containing the properties Ticket, NetId and IsValidated. The only method is Validate, which performs a once-only validation of the ticket ID. The result of the validation is stored in property IsValidated. If more than one validation is attempted on the same ticket ID, CAS would throw an exception.

The content of a successful validation response contains the user login (i.e. the netid) and the method parses and stores it in its NetId property.

public bool Validate(HttpRequest request, HttpResponse response)
{
    if (!IsValidated)
    {
        string service = request.Url.GetLeftPart(UriPartial.Path);
        string validateUrl = string.Format(VALIDATE_URL, CASAuthenticator.CASHOST, Ticket, HttpUtility.UrlEncode(service));
        StreamReader reader = new StreamReader(new WebClient().OpenRead(validateUrl));

        XPathNavigator navigator = new XPathDocument(reader).CreateNavigator();
        XmlNamespaceManager namespaceManager = new XmlNamespaceManager(navigator.NameTable);
        namespaceManager.AddNamespace("cas", CAS_NAMESPACE);

        XPathNavigator userNavigator = navigator.SelectSingleNode("//cas:user", namespaceManager);
        if (userNavigator != null)
        {
            NetId = userNavigator.Value;
        }

        reader.Close();
    }

    IsValidated = !string.IsNullOrEmpty(NetId);

    return IsValidated;
}

I devised the whole mechanism of caching the CASTicket in a web cache, such that the validation of a CAS ticket only happens once, but its result is kept in cache and made available for subsequent requests. The cache duration is configurable. This duration specifies the 'length' of the logged in session.

The value of the 'ticket' cookie is an MD5 of the ticket ID. This is by no means intended to be secure or encrypted. Instead is simply exposes an already validated CAS ticket, while keeping secret the netid and its authenticated state. The cookie is set as session only, so it's deleted after the browser is closed.



Comments

Popular posts from this blog

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as...

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl...

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when...