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

Content Delivery Monitoring in AWS with CloudWatch

This post describes a way of monitoring a Tridion 9 combined Deployer by sending the health checks into a custom metric in CloudWatch in AWS. The same approach can also be used for other Content Delivery services. Once the metric is available in CloudWatch, we can create alarms in case the service errors out or becomes unresponsive. The overall architecture is as follows: Content Delivery service sends heartbeat (or exposes HTTP endpoint) for monitoring Monitoring Agent checks heartbeat (or HTTP health check) regularly and stores health state AWS lambda function: runs regularly reads the health state from Monitoring Agent pushes custom metrics into CloudWatch I am running the Deployer ( installation docs ) and Monitoring Agent ( installation docs ) on a t2.medium EC2 instance running CentOS on which I also installed the Systems Manager Agent (SSM Agent) ( installation docs ). In my case I have a combined Deployer that I want to monitor. This consists of an Endpoint and a

Debugging a Tridion 2011 Event System

OK, so you wrote your Tridion Event System. Now it's time to debug it. I know this is a hypothetical situtation -- your code never needs any kind of debugging ;) but indulge me... Recently, Alvin Reyes ( @nivlong ) blogged about being difficult to know how exactly to debug a Tridion Event System. More exactly, the question was " What process do I attach to for debugging even system code? ". Unfortunately, there is no simple or generic answer for it. Different events are fired by different Tridion CM modules. These modules run as different programs (or services) or run inside other programs (e.g. IIS). This means that you will need to monitor (or debug) different processes, based on which events your code handles. So the usual suspects are: dllhost.exe (or dllhost3g.exe ) - running as the MTSUser is the SDL Tridion Content Manager COM+ application and it fires events on generic TOM objects (e.g. events based on Tridion.ContentManager.Extensibility.Events.CrudEven