How to add support for Federated Authentication and claims to Sitecore using OWIN

Out of the box, Sitecore only offers their own forms-based authentication provider, which requires to add every user to the Sitecore membership database. At Achmea, we had the requirement to facilitate login via ADFS, as we are using our user accounts amongst different systems, web applications and apps. In addition to the absence of this functionality, it’s not possible to work with claims as well.

This blogpost describes how to add and use the Federated Authentication middleware using OWIN in combination with Sitecore and how to access the claims that are provided using the federated login. The solution supports a multi-site scenario, which can handle different identity providers and multiple realms. This opens up possibilities to use external identity providers, for example via ADFS or Windows Azure Active Directory.

The source code for federated login component can be found on github. Please feel free to contact me via twitter/mail/github if there are any questions! A special thanksto Kern Herskind Nightingale of Sitecore: We discussed a lot on the integration patterns for Federation and Sitecore.

Why not to use the ADFS Authenticator Marketplace module?

During my quest on integrating Federated Authentication with Sitecore, I found this module. I had some issues to get it to work in Sitecore 8 build 5, (although I managed to get it to work), but there were some drawbacks why I decided not to use this module:

  • Microsoft is putting their bets on OWIN. As I expect that Sitecore will go that direction in the future, I want to write software that can be easily migrated to future products. (That’s why we don’t create webforms solutions anymore as well)
  • Some extra pipelines were added for User resolving and token requesters.
  • I had to add a few extra HttpModules
  • It didn’t support multiple sites and multiple realms in a secure way

The Sitecore architecture

Basically, the default user management implementation for Sitecore, is a custom Forms Authentication Provider, which makes use of the default ASP.Net Forms Authentication implementation. Under the hood, these users are partially managed in a standard Asp.Net Membership database. For example, information like roles, passwords, and user statuses are all managed in this membership database.

The Sitecore implementation lies around the FormsAuthenticationProvider and FormsAuthenticationHelper, which both exist in the Sitecore.Security.Authentication namespace in the Sitecore.Kernel assembly.

Upon login, there is an Authentication manager which has all login and user management logic abstracted away. The FormsAuthentication Manager, which has been registered in the web.config, is injected in the Authentication Manager as an Authentication Provider. Under the hood, the following actions happen:

  • Username and password are being validated
  • A new Sitecore User object is created
  • The Sitecore user object will be assigned to the HttpContext.Current.User and Thread.CurrentPrincipal

Challenges with OWIN and Sitecore

Adding the OWIN Federated Authentication middleware isn’t too hard (more on that matter later). There are a number of challenges, which can be found in the combination of the federated authentication and Sitecore.

Authentication Challenge

In Sitecore, the AuthenticationManager.Login(username, password) is being used. As stated before, the used Provider is configurable within the web.config. This requires a custom Authentication Provider implementation and a custom Authentication Helper implementation. As this is a serious job that has to be done, I was a bit reluctant to use this. It replaces some out of the box functionality, something I want to prevent as much as possible.

Lifecycle challenge

It can be quite complex to determine when the Claims principal is available, complete and how to map it on the Sitecore user objects.

Claims challenge

Due to the fact that the Thread.CurrentPrincipal and the HttpContext.Current.User object are both being replaced with the Sitecore User object, the provided claims are not available anymore. Solving this in the Sitecore pipeline is not possible, as the claims property is not available on the User class. Replacing the Sitecore User object with another User object would seriously break Sitecore. Writing custom logic to create a custom Sitecore ClaimsUser object would be a serious effort and I don’t know whether or not that would even be possible, due to the internal usage of the Sitecore User object.

Multiple site challenge

The WsFederation Authentication Middleware does not support multi-tenancy: configuring a single instance of authentication middleware with different hostnames and realms that need to be accepted is not possible.

Luckily, all of these challenges can be encountered! As I wrote in some of my previous blogposts, adding OWIN Federation middleware is quite easy. But for the sake of completeness in my first serious Sitecore blogpost, I’ll describe this process later on in this blogpost.

Configuring OWIN in Sitecore

We’ll start with a simple, plain OWIN configuration, which injects the Cookie Authentication module and the WsFederation Authentication Module. The WsFederation Authentication module handles the initial authentication challenge and redirects the user to, in this case, my own STS. When the RST has been returned, the WsFederation Authentication module handles and verifies this token, while the Cookie Authentication module creates a “.AspNet.Cookies” cookie (often referred to the claims cookie), which contains all the user information.

Both middlewares can have several configuration options and events attached: we’ll get into some of those later on.

Federated login for Sitecore – the login flow

When a page is requiring a login, the pipeline could handle the login challenge. I chose to redirect the user to a login page. On this page, there is a controller rendering, whose action is decorated with the [Authorize] Attribute. This attribute does not cause a Sitecore Forms authentication challenge, but a plain ASP.Net authentication challenge, the one that has been configured with OWIN.

The OWIN middleware handles the RST token and sets the claimcookie and sets the current identity on Thread.CurrentPrincipal and HttpContext.Current.User. After handling this token, the Controller logic can be executed and the user will be redirected to the original, requested page.

At this point, there is still no Sitecore user identity. The result: The user gets redirected back to the login page, the authentication challenge will not be triggered, as the claims cookie is available.

Right now we are are missing logic to do an actual “Sitecore user login”. There are bootstrap options to do this:

  • On the SecurityTokenValidated event of the WsFederationAuthentication middleware
  • In the Sitecore pipeline
  • In the login controller action

But before we can do the actual bootstrap, another problem has to be solved.

Supress Form validation when ADFS posts the RST to Sitecore

The RST that is posted to Sitecore by ADFS, needs to be handled. At the moment of writing, there is a PreProcessRequest processor, which handles form posts to Sitecore, the SuppressFormValidation processor.

This processor throws an exception if an unsafe form post was found, but adds some exceptions to Sitecore: unsafe form posts to “/Sitecore/shell” and “/Sitecore/admin” are allowed. Unfortunately, these paths are not configurable, thus I replaced that processor by this implementation:

public override void Process(PreprocessRequestArgs args)
    Assert.ArgumentNotNull(args, "args");
        new SuppressFormValidation().Process(args);
    catch (HttpRequestValidationException)
        string rawUrl = args.Context.Request.RawUrl;
        if (!rawUrl.Contains("login"))

These solution respects the original processor outcome, catches the exception, but adds a path that should accept an unsafe formpost as well. In any other situation: rethrow the same exception, this causes Sitecore to behave exactly the same as it did before.

The bootstrap moments


This event seems the most logic place to login the Sitecore user, but it has a major drawback. At the moment that the RST has been validated, a Claimcookie hasn’t been created yet by the Cookie Authentication middleware. The Authentication Ticket, however, is available. When a virtual user is being created, the actual claims from the ticket can be mapped to this user (for example to map some Sitecore user roles), but at the moment that AuthenticationManager.Login() has been called, the HttpContext.Current.User and Thread.CurrentPrincipal properties are being overwritten with Sitecore user. All of your claims, that weren’t mapped to the Sitecore user, are lost.

If there is no need to use claims in your custom code, or the use of the Sitecore roles is sufficient, this is the best place to do the user login, however, if you are in need of using claims, this moment cannot be used as a bootstrap moment.

Sitecore pipeline

As the Sitecore pipeline is highly extensible, this might be a good solution as well. But I wanted to keep the login logic as far away from Sitecore as possible, as it might introduce unwanted complexity, so I didn’t investigate this option further. If anyone has some good reasons to put the logic in a processor, please share these reasons with me!

Controller action

I chose the controller action as bootstrap moment: After being returned from ADFS, the Claim cookie has already been generated. In the controller action logic, the claim cookie is accessible, while the user hasn’t been logged in to Sitecore yet. This is the moment do the Sitecore login and execute some additional actions.

Logging a Sitecore user and mapping claims to Sitecoreroles

As stated before, at the moment that the controller action is being executed, the user can be logged in to Sitecore. I have reused the code that was written by Vasiliy Fomichev. He created a login helper as part of the ADFS Authenticator solution, which is available on github. This loginhelper compares all roleclaims to the Sitecore groups. For every positive result, that Sitecore group is being added to the virtual Sitecore user. After the group assignment has been finished, the virtual user is logged in to Sitecore. The implementation of the loginhelper can be found here.

Mutiple sites configuration

With this OWIN configuration, the multi site requirement hasn’t been fulfilled yet. As the WsFederationAuthentication middleware does not support multi-tenancy, another solution was needed. This solution could be achieved by making use of the pipeline-branching options of the OWIN pipeline.


OWIN supports pipeline branching. app.Map or app.MapWhen can be used to inject some middleware to a specific path or to a specific situation. In my case, I could use the app.MapWhen option:

app.MapWhen(ctx => ctx.Request.Get("host").Equals("multisite.local"), site => { Console.WriteLine("branch 1"); });

I used this technique to register all my sites together with its specific middleware. This can be hardcoded, but it’s better to provide the configuration in a separate configuration file, as it doesn’t require a redeployment when a Sitecore site has been added. An addition of a new option, however, does require an application pool recycle in IIS

The claims challenge

The claims challenge was a harder one to tackle. In a normal Asp.Net webapplication, we can retrieve our claims from the Claimsprincipal that is assigned to the HttpContext.User property. But as Sitecore overwrites this property, we can’t retrieve those claims.

Because of the choice I made for the bootstrap moment, I have access to the .AspNet.Cookies cookie, in which the claims identity is stored. On every request, this cookie is being decrypted and deserialized by the OWIN middleware, to provide the identity. And again, after that moment, Sitecore is overwriting that identity with its Sitecore user.

Retrieving the AuthenticationTicket

The cookie value can easily be retrieved, but it’s encrypted. When adding the CookieAuthenticationOptions to the CookieAuthenticationMiddleware, the TicketDataFormat is being set. This is a property which helps storing the AuthenticationTicket in a cookie. The default implementation even encrypts this data:

if (base.Options.TicketDataFormat == null)
    IDataProtector protector = app.CreateDataProtector(new string[]
    base.Options.TicketDataFormat = new TicketDataFormat(protector);

As the dataprotector is used internally by the middleware, it was hard for me to decrypt that data in the cookie. By providing an own dataprotector to the TicketDataFormat, it’s easy to decrypt the cookiedata and return the AuthenticationTickets by decrypting the cookies:

internal class MachineKeyProtector : IDataProtector
    private readonly string[] _purpose =

    public byte[] Protect(byte[] userData)
        return System.Web.Security.MachineKey.Protect(userData, _purpose);

    public byte[] Unprotect(byte[] protectedData)
        return System.Web.Security.MachineKey.Unprotect(protectedData, _purpose);

This function can be used to get the AuthenticationTicket from the cookie:

private static AuthenticationTicket GetAuthenticationKeyTicket()
AuthenticationTicket ticket = null;

var ctx = HttpContext.Current.Request;
if (ctx.Cookies != null && ctx.Cookies[“.AspNet.Cookies”] != null)
var cookie = ctx.Cookies[“.AspNet.Cookies”];
var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
ticket = secureDataFormat.Unprotect(cookie.Value);
return ticket;


And within that Ticket, the ClaimsIdentity can be found:

// Summary:
//     Contains user identity information as well as additional authentication state.
public class AuthenticationTicket
// Summary:
//     Initializes a new instance of the Microsoft.Owin.Security.AuthenticationTicket
//     class
// Parameters:
//   identity:
//   properties:
public AuthenticationTicket(ClaimsIdentity identity, AuthenticationProperties properties);

// Summary:
//     Gets the authenticated user identity.
public ClaimsIdentity Identity { get; }
// Summary:
//     Additional state values for the authentication session.
public AuthenticationProperties Properties { get; }

SessionStore to prevent replay attacks and keep the cookies small

In addition to this TicketDataFormat, I decided to implement the SessionStore property as well. When this property is not null, the OWIN middleware doesn’t store the complete claimsidentity, with all it’s claims, into the cookie, but just a reference to it: this keeps the cookies small. For an explanation see this blogpost on reference mode by Vittorio Bertocci. I also used his code.

A great and safe side effect, is that there is a server side storage which can be used verify if identities are still valid.

In normal FormsAuthentication scenario’s (like Sitecore has), a user can logout. All that happens, is that the cookie gets deleted. When someone intercepts that cookie, for example on a public machine, that person could restart the website, add that cookie and he is logged in again.

When using this SessionStore technique, just the reference to the cookie is being stored and the real AuthenticationTicket can be deleted when a user logs out. When a malicious person is adding the stolen cookie to a new browser session, he won’t be able to steal your identity anymore. I’ll write more on this subject in a future blogpost.

The lifecycle challenge

Last, but not least, I had to cope with the lifecycle challenge. As we are working with two identities, they have to aligned which each other: The Sitecore identity (represented by the .aspxauth cookie) and the OWIN identity (represented by the .AspNet.Cookies cookie and the session store). I put the OWIN identity as leading Identity; when this identity is not valid, available, expired, or whatsoever, then the Sitecore identity should be invalidated as well. In all other cases, the identities should match or not be available at all, to represent a valid request.

After the user resolver processor in the HttpRequestBegin pipeline, I added a new processor, which checks the authentication status. I created the following table for it:

  fedAuth cookie Claims Principal Sitecore User Status Beschrijving Handled by
1 0 0 0 OK No identification options available: anonymous request Pipeline
2 1 0 0 NOK Cookie not valid: delete and redirect to login page Handled by OWIN
3 0 1 0 OK No identification possible. Token is automatically deleted by cleanup job. Anonymous request Pipeline
4 1 1 0 NOK No corresponding Sitecore ID – delete cookie and token. Sitecore handles redirect to login if needed Pipeline and Sitecore
5 0 0 1 NOK Logout, redirect to login page Pipeline
6 1 0 1 NOK Cookie not valid: delete, logout and redirect to loginpage Pipeline
7 0 1 1 NOK No identification possible, same situation as 5: logout Sitecore user and redirect to loginpage Pipeline
8 1 1 1 OK Valid situation. Validate both identities, if they correspond with each other, valid request. Otherwise: logout and redirect to loginpage Pipeline

Basically, it comes down to 3 valid situations, of which 2 reside in valid anonymous request and only the last one leads to a valid authenticated request.


Adding Federated authentication to Sitecore using OWIN is possible. In the end, the solution wasn’t too complex and makes use of standard Sitecore where possible, without intervening in it’s core logic. Using ASP.Net for authentication on top of Sitecore as a kind of passthrough authentication layer, keeps us safe and it can easily be removed.


Setup your development environment for High trust Saml Claims based SharePoint provider hosted applications using OWIN and an easy to use STS – part 3

Since SharePoint 2013, web applications are created with claims based authentication by default. This works with together with High trust provider hosted apps, based on windows authentication as well. Whenever ADFS with its SAML claims pops in, it gets complicated: SharePoint needs to be configured, High trust provider apps need to configured and the app needs to communicate with SharePoint – using saml claims. Mix in a development environment, where, very likely, no ADFS is available and it gets complicated. Until now ;).

This blogpost describes how to setup an identity provider STS for development environments, how to configure SharePoint to use this STS and how to develop a web application that uses SAML claims and can communicate with SharePoint. All using OWIN, as it easens up development. More information on the STS and the OWIN configuration can be found in my previous blogpost in this series:

Continue reading


Configure claims based web applications using OWIN WsFederation middleware

In my previous blogpost about setting up a simple STS for web application development I wrote on how to setup this web application using the classic web.config modifications. But this can be a lot easier, by using the OWIN middleware WsFederation module. This blogpost describes how to setup a secured web application using the OWIN WsFederation modules; This is the second blogpost in a blogpost series of three, where we work towards a simple (local development) solution to build High trust claims based SharePoint provider hosted apps .

  1. How to setup a simple STS for web application development
  2. How to configure WsFederation for webapplications using OWIN (this blogpost)
  3. How to mix in SharePoint 2013 and hight trust claims based provider hosted apps using OWIN and the thinktecture Embedded STS

Configuration using OWIN

OWIN is the Open Web Interface for .Net. The definition according to

OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.

Freely explained: it defines a standard interface between .Net web servers and web applications and should make it possible to run ( web applications on other servers than, for example, IIS. In this case, the OWIN modules for WsFederation make it very easy to configure authentication, as opposed to the classic web.config configuration. Daniel Roth summarized it in one simple image in his blogpost:

configuration comparison between web.config and OWIN - property of Daniel Roth

configuration comparison between web.config and OWIN – property of Daniel Roth

Why so easy?

The WsFederation module can be configured in such a way, that it requests the federation metadata of the STS. This Federation metadata contains information on the Identity Provider with information on the signing certificates, provided claims and much more info, which normally have to be configured by hand, which often go wrong. All other information that has to be provided, is the requested realm.

In the case of the Thinktecture Embedded STS, there was no Federation Metadata endpoint, but I added one and offered it as a pull request to the owners of the Embedded STS. Writing one was pretty simple, but getting it to work, caused a major “challenge”: I had some severe issues to get the endpoint to work, but hey, I got the job done ;).

This STS is so easy, because it doesn’t require any form of setup:

  1. Edit the EmbeddedStsUsers.json, to add users and/or claims
  2. Run the application

In addition to the easy setup, it always returns the information you request, without the hassle of configuring reply-addresses, realms, claim rules or whatever – the perfect solution when developing new webapplications!

How to configure

To create a webapplication that makes use of OWIN, do the following:

  • Create a new web application
  • Install OWIN and the WsFederation middleware
  • Configure the application
  • Run

Create a new webapplication

First, create a new webapplication. It doesn’t matter which kind of application you choose, it works both with Webforms and MVC web applications. Make sure to choose “No Authentication” in the wizard, as the authentication will be handled by the middleware, not by the build-in ASP.Net authentication facilities.

Second, make sure to add an “Authorize” attribute to the landing page or HomeController, this forces and authentication challenge. All logged in people will have access to this resource.

Make sure to use the attribute in System.Net.Http for webforms, and System.Net.Mvc for MVC applications

Install OWIN and the WsFederation middleware

Install the required packages using the following commands:

  • install-package Microsoft.OWIN – this installs OWIN and the Microsoft.OWIN modules in your webapplication
  • install-package Microsoft.OWIN.Host.SystemWeb – this one injects the Microsoft OWIN infrastructure
  • install-package Microsoft.Owin.Security.WsFederation – installs the WsFederation middleware and all prerequisites
  • install-package Owin.Security.Cookies

Configure the application to run the middleware

First, the application needs to be configured to run the OWIN middleware. To do this, add a new class. This class is initialized on startup when marked with the OWIN startup attribute. A template has been provided: Make sure to choose the OWIN startup template when creating the new class:

The template looks as follows:

The namespace has been marked with the OwinStartUp attribute. This means for this assembly that the Startup1 class will be used to configure the application. The Configuration class will always be used to configure the application and accepts an IAppBuilder parameter as input. This is the generic interface to configure OWIN middleware. The

The next, and last step, is to configure the application to use the WsFederation middleware:

public void Configuration(IAppBuilder app)
app.UseCookieAuthentication(new CookieAuthenticationOptions());
new WsFederationAuthenticationOptions
MetadataAddress = "http://localhost:29702/FederationMetadata",
Wtrealm = "urn:SupaDoopaRealm",
Wreply = "http://localhost:16635/"

Line 5 configures the default login option to use “Cookies”. In this example, we use a constant string to specify this, but a plain old string with the text “Cookies” will be sufficient as well.

Line 6 sets the authentication options for the Cookie Authentication, which is empty in this case.

Line 8 is the line of code, where all the magic happens. The WsFederationAuthentication module is loaded, with 3 parameters:

  • MetadataAddress – endpoint where to get the wsfederationmetadata from
  • Wtrealm: the requested realm – in the case of the thinktecture embedded STS, this can be any value, is it always returns the requested realm
  • Wreply – Normally, this parameter can be specified on the STS itself, but in case of the EmbeddedSTS, this parameter has to be provided, otherwise, you’ll be redirected to the STS itself.


Hit F5 and see the magic happen. Whenever you press the login button, you’ll be redirected to the EmbeddedSTS, because the Authorize attribute triggered the authentication challenge:

After signing in, you are authenticated and redirected to the page that triggered the challenge. And because all logged in users are authorized in this example, you will have permission to view the page.


Setup claims based authentication in a web application using OWIN is very easy, it just consists of pulling in a few packages, define a startup class, and configure the WsFederation Middleware. It’s way easier then doing this manually, due to the fact that the magic is handled by the middleware, using the WsFederation Metadata.

Next blogpost will explain on how to use the Embedded STS, SharePoint 2013 and High trust Claims based provider hosted applications using OWIN. That’s a mouth full for a title 😉

The Embedded STS sources can be downloaded here (own fork of the Thinktecture.IdentityModel).

The example project for configuring claims based web applications using OWIN can be found here.

Embedded STS Sample

How to setup a simple STS for web application development – Part 1 of 3

When developing claims based web applications which need to connect to ADFS, Azure or any other STS, it’s not always possible to connect to an existing environment, for example, due to security, the absence of a test environment or an unwilling admin ;). To solve this, a lot of people try to setup a local AD, ADFS, which can cause a lot of trouble, especially in an Enterprise environment. This setup is not very convenient, especially when you just want to create a claims based application. Whenever SharePoint and Claims based hight trust provider hosted apps are thrown into the game, the inconvenient setup turns into a very complex situation.

Luckily, there is a very easy solution for this! In the next two blogposts I will show to solve this:

  1. How to setup a simple STS for web application development (this blogpost) – how to create a simple STS using Thinktecture embedded STS and configure the web application using the classic web.config
  2. How to setup claims based authentication via OWIN
  3. How to mix in SharePoint 2013 and hight trust claims based provider hosted apps using OWIN and the thinktecture Embedded STS

Continue reading


Claims based authentication – The signature verification failed

I was working on a small addition to the Thinktecture EmbeddedSTS, to ease up local development for our development teams, who are building a lot of MVC applications and SharePoint provider hosted apps. We don’t want to bother them with setting up a separate AD and ADFS, so we decided to use a simple, small STS: the Thinktecture Embedded STS. One of the actions was to add a FederationMetdata endpoint. This is a small improvement, as it’s now possible to setup claims based identities via OWIN, which is way easier to setup than via the typical web.config configuration. But there was one nifty error that was, in my case, very hard to find, but easy to fix. It turned out that the signature node may not contain any formatting, this means that spaces, line feeds and carriage returns should not be included in this Federationmetadata file

Continue reading

Create an organizational account to administrate azure when having a Microsoft Account

When you created your Microsoft Azure subscription with a personal Microsoft Account, it’s likely that you won’t be able to use some azure services, for example, the new Power BI service, as they require an organizational account. This blogpost describes on how to create an organizational account and delegate the azure administrator role to this account, so you’ll be free to use any azure service.

Continue reading

sitecore rocks banner

How to use Sitecore Rocks with Visual Studio 2015 preview

If you want to use the recently released Visual Studio 2015 preview together with Sitecore rocks for sitecore development, you won’t be able to install this plugin from the Visual Studio Extensions gallery: you won’t even find installable plugin while searching for the plugin. This blogpost describes how to get this plugin to work.

Continue reading

Getting SharePoint 2013 apps and WebAPI to work

With the release of Visual Studio 2013, Microsoft also added a very nice MVC template for remote SharePoint Apps. This is a slightly modifed version of the default MVC5 template, which doesn’t, for example, contain an own authentication provider, but does contain all the stuff like bootstrap and the latest jquery version. Some extra helper files have been added (via a nuget package) to assist in the communication with SharePoint 2013. This does work perfectly with the Actions defined in MVC controllers, but the code doesn’t work together with ApiControllers. Yet 😉 This blogpost shows us how (roughly) the same functionality can be implemented for use with the WebApi controller! At the end, the full source code is provided, it works in azure, as well as with high trust solutions. A good read on the basics of the SharePointContextProvider can be found here and here

Note: the provided code is by no means production ready! I didn’t test it thoroughly, but the basic scenario’s do work!

Continue reading

Convert MVC application to SharePoint 2013 provider hosted app

With the introduction of the SharePoint App model, it becomes more and more interesting to convert existing applications in your organisation from a “plain” MVC application to a SharePoint app. This makes it easy to integrate SharePoint capabilities such as Search, UserProfiles and newsfeeds within your application, to make it even cooler! This blogpost describes the steps that are required to convert a MVC application to a SharePoint 2013 app using Visual Studio 2013

Continue reading