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...

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl...

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when...