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

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

SDL Web 8 - Content Delivery Microservices

Among the new features in SDL Web 8 there are the Content Delivery Microservices, namely: Audience Manager Content Deployer Contextual Image Delivery Discovery Service Dynamic Content Dynamic Linking Profiling and Personalization Metadata Query Taxonomy User Generated Content These microservices make up the Content Interaction Services and they expose the existing Content Delivery in-process APIs as RESTful services. They provide the server-side component in a Services-Oriented Architecture and act as data layer between the the web client and the Content Delivery Storage Layer. According to the SDL marketing, these microservices: Simplify upgrades, thus offering shorter time to value Modernize architecture, offering better separation between the web application and Tridion APIs Offer more flexibility with less downtime and improved scalability Improve quality, being self-running, contained and having less dependencies In technical words, these microservices