ASP.NET Web API Security: The Thinktecture.IdentityModel AuthenticationHandler

AuthenticationHandler is an ASP.NET Web API message handler that can map incoming credentials to a token handler. The token handler in turn can parse credentials and create a principal.

In addition AuthenticationHandler provides some common services like claims transformation, session tokens and handling of response headers.

AuthenticationHandler

Your job is to do provide the mapping between credential and token handler, e.g.

  • Basic Authentication credentials on the Authorization header
  • JWT or SAML token on the Authorization header
  • Client certificate
  • Access key on the query string
  • Signature over incoming HTTP request

…and which authentication hint gets sent back (along the 401 status code).

For this definition you use the AuthenticationOptionMapping class:

var mapping = new AuthenticationOptionMapping

{

    // where to look for credentials

    Options = options,

               

    // how to validate them

    TokenHandler = handler,

               

    // which hint to give back if not successful

    Scheme = scheme

};

Options could be e.g.:

  • the Authorization header (with some scheme)
  • some other HTTP header
  • a query string parameter
  • a client certificate
  • a cookie

Thinktecture IdentityModel comes with several pre-defined token handlers, e.g.

  • JWT, SWT and SAML tokens
  • Basic Authentication
  • client certificates
  • access keys

…and last but not least, you have control over the Www-Authenticate header that get’s sent back if authorization was not successful, e.g.

  • some scheme and some realm
  • scheme only
  • scheme and some challenge

You can add all required associations to the authentication configuration:

var config = new AuthenticationConfiguration
{
    RequireSsl = true
};
 

config.AddMapping(mapping);

…and finally add the handler to the Web API runtime:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
 
var authConfig = ConfigureAuthentication();
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));

 

After that, authentication handler will inspect every request, look for credentials, and if successful create and populate the principal.

HTH

This entry was posted in IdentityModel, OAuth, WebAPI. Bookmark the permalink.

12 Responses to ASP.NET Web API Security: The Thinktecture.IdentityModel AuthenticationHandler

  1. Pingback: Web API Security: Basic Authentication with Thinktecture.IdentityModel AuthenticationHandler | www.leastprivilege.com