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

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

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