Skip to main content

Basic Authenticator Web 8.5 with ADFS

This post presents a Basic Authenticator wrapper around ADFS security. This authenticator allows a client and web-service to use Basic authorization security, while the actual security authentication happens on an ADFS server.

The Basic Authenticator is a .NET HTTP module, which creates a security context based on a user principal that it receives from ADFS. All subsequent request processing happens in the context of this 'impersonated' context.

The request processing sequence is as follows:
  1. Client connects to web-service using Basic authorization (over HTTPS, so the Authorization request header is not transmitted in the open)
  2. Basic Authenticator HTTP module intercepts the request
  3. If Authorization header is in the request
    1. Extract and decode username/password from Authorization header
    2. If username/password is valid in ADFS
      1. Create user principal
      2. Set security context
      3. Let request processing continue
    3. Else
      1. Send 401 WWW-Authenticate response header
      2. Stop request processing
  4. Else
    1. Send 401 WWW-Authenticate response header
    2. Stop request processing

Request processing starts with AuthenticateRequest method. If there is an Authorization header, then try extract and validate user with ADFS; otherwise, prepare to return 401 response.

public void AuthenticateRequest()
{
    var authorization = Request.Headers["Authorization"];
    if (authorization != null)
    {
        string credentials = GetCredentials(authorization);
        if (credentials != null && AuthenticateUser(credentials))
        {
            Request.Headers[Configuration.HeaderUser] = HttpContext.Current.User.Identity.Name;

            return;
        }
    }

    HttpContext.Current.Response.StatusCode = 401;
}

The request processing ends with method EndRequest. If the response code was set to 401, then send a WWW-Authenticate header also to force the client to send a request header Authorization. Unless the request type is OPTIONS (which means it is a WebDAV request), in which case we send back 200 OK.

public void EndRequest()
{
    if (Response.StatusCode == 401)
    {
        if (Request.RequestType == "OPTIONS")
        {
            Response.StatusCode = 200;
        }
        else
        {
            Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm));
        }
    }
}

Method GetCredentials decodes the Authorization header and extracts the username/password:

private string GetCredentials(string authorizationHeader)
{
    var headerValue = AuthenticationHeaderValue.Parse(authorizationHeader);
    if (!headerValue.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) ||
        string.IsNullOrEmpty(headerValue.Parameter))
    {
        return null;
    }

    var encoding = Encoding.GetEncoding("iso-8859-1");
    byte[] credentialsBytes = Convert.FromBase64String(headerValue.Parameter);

    return encoding.GetString(credentialsBytes);
}

Next, the AuthenticateUser method is called in case we have a successfully extracted username/password from the Authorization header. This method checks the credentials agains ADFS and sets the security context both in current HttpContext and current Thread objects.

private bool AuthenticateUser(string credentials)
{
    IPrincipal principal = CheckPassword(credentials);
    if (principal != null)
    {
        Thread.CurrentPrincipal = principal;
        HttpContext.Current.User = principal;

        return true;
    }

    return false;
}

Next, the method CheckPassword is where the credentials are checked against ADFS. If successful, ADFS returns a SAML token, which we need to decrypt, extract the user from it, and then create a user principal for this user:

private ClaimsPrincipal CheckPassword(string credentials)
{
    string[] parts = credentials.Split(':');
    if (parts.Length != 2)
    {
        return null;
    }

    AdfsClient adfsClient = new AdfsClient(parts[0], parts[1],
        Utils.Configuration.AdfsAudienceId, Utils.Configuration.AdfsStsUrl);
    GenericXmlSecurityToken encryptedToken = adfsClient.GetToken();
    SecurityToken decryptedToken = adfsClient.DecryptToken(encryptedToken);

    return adfsClient.GetPrincipal(decryptedToken);
}

The code above makes use of a custom class AdfsClient that abstracts out the interaction with the ADFS server. The main methods are the following:
  • GetToken: requests a SAML token from the ADFS server, passing in the user, password and Relying Party identifier and returns an XML representation of the token;
  • DecryptToken: decrypts the encrypted SAML token and converts it into a Saml2SecurityToken;
  • GetPrincipal: extracts the ClaimsIdentity from the decrypted SAML token and returns a ClaimsPrincipal;

For brevity, I won't go into details about the AdfsClient class in this blog post. Instead, I will dedicate an entire blog post to AdfsClient shortly.



Comments

Popular posts from this blog

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

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

Event System to Create Mapped Structure Groups for Binary Publish

As a continuation of last week's Publish Binaries to Mapped Structure Group , this week's TBB is in fact the Event System part of that solution. Make sure you do check out the previous post first, which explains why and what this Event System does. To reiterate, the Event System intercepts a Multimedia Component save, take its Folder path and create a 1-to-1 mapping of Structure Groups. The original code was written, again, by my colleague Eric Huiza : [ TcmExtension ( "MyEvents" )] public class EventsManager  : TcmExtension {     private Configuration configuration;     private readonly Regex SAFE_DIRNAME_REGEX = new Regex ( @"[\W_]+" );     public EventsManager() {         ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap ();         fileMap.ExeConfigFilename = Path .GetDirectoryName( Assembly .GetExecutingAssembly().Location) + "\\EventSystem.config" ;         configuration = ConfigurationManager