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

Scaling Policies

This post is part of a bigger topic Autoscaling Publishers in AWS . In a previous post we talked about the Auto Scaling Groups , but we didn't go into details on the Scaling Policies. This is the purpose of this blog post. As defined earlier, the Scaling Policies define the rules according to which the group size is increased or decreased. These rules are based on instance metrics (e.g. CPU), CloudWatch custom metrics, or even CloudWatch alarms and their states and values. We defined a Scaling Policy with Steps, called 'increase_group_size', which is triggered first by the CloudWatch Alarm 'Publish_Alarm' defined earlier. Also depending on the size of the monitored CloudWatch custom metric 'Waiting for Publish', the Scaling Policy with Steps can add a difference number of instances to the group. The scaling policy sets the number of instances in group to 1 if there are between 1000 and 2000 items Waiting for Publish in the queue. It also sets the

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

Toolkit - Dynamic Content Queries

This post if part of a series about the  File System Toolkit  - a custom content delivery API for SDL Tridion. This post presents the Dynamic Content Query capability. The requirements for the Toolkit API are that it should be able to provide CustomMeta queries, pagination, and sorting -- all on the file system, without the use third party tools (database, search engines, indexers, etc). Therefore I had to implement a simple database engine and indexer -- which is described in more detail in post Writing My Own Database Engine . The querying logic does not make use of cache. This means the query logic is executed every time. When models are requested, the models are however retrieved using the ModelFactory and those are cached. Query Class This is the main class for dynamic content queries. It is the entry point into the execution logic of a query. The class takes as parameter a Criterion (presented below) which triggers the execution of query in all sub-criteria of a Criterio