Making Ajax play with Passive ADFS 2.1 (and 2.0) – Reactive Authentication

The first post, described the issue of using ADFS and Ajax to create SSO between a WebApp and a WebAPI. This solution looks at the changing the WebAPI to return 401 if the request is not authorized and then using an iFrame to authenticate the user for subsequent calls.

The last solution, pre-authorized on the first AJAX call per page load, which adds some overhead. This was because JSONP has no means of returning status codes (this is not entirely true, you can return a 200 and then have the real response inside a payload, but that is beyond this article). This solution makes use of normal AJAX calls and 401 responses to perform authorization only when it is required.


  • This uses normal AJAX calls, so it requires CORS to be enabled on the WebAPI server for cross-domain requests. (See this guide)
  • IE8 & 9 do not support the passing of cookies with cross domain requests and therefore this method will not work as described. However, it should be possible to pass the token in the body of the AJAX request (use POST and HTTPS to maintain security) and write a customized AuthenticationModule to read the token and provide it to the WSFederatedAuthenticationModule. (This is outside the scope of this solution however)


By default, the WSFederationAuthenticationModule redirects the user to ADFS if the user is not currently authenticated (there is no valid session cookie). This can be changed with the following code

FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += (sender, e) =>
    if (Context.Request.RequestContext.HttpContext.Request.IsAjaxRequest())
        e.RedirectToIdentityProvider = false;

By adding this code to ApplicationStart, or a HttpModule, we can make the WebAPI return a HttpStatus of 401 every time authentication is required (during an AJAX request). We then handle this response in our javascript.

The following Gist shows some javascript that handles the 401 response and then uses the idea of authenticating in a iFrame from the last solution, before retrying the AJAX call. The second attempt should now have the needed session cookies to authorize and succeed.


Making Ajax play with Passive ADFS 2.1 (and 2.0) – JSONP & Pre-Authentication

The first post, described the issue of using ADFS and Ajax to create SSO between a WebApp and a WebAPI.
This solution looks at using JSONP and pre-authentication to achieve SSO between sites on different domains.

Solution Overview

We add a html page (or handler) to the WebAPI solution.
Whenever we make a call to the WebAPI we first load the html page in an iFrame, this iFrame call handles all the ADFS redirects and sets the session cookies for the WebAPI.
These session cookies are then sent (automatically) with the next JSONP call to the server.


  • Like all the solutions, this expects that the user has authenticated with ADFS via the WebAPP. When the iFrame hits the WebAPI pre-auth html page and the request gets redirected to ADFS if the user already has a session (that is compatible with the WebAPI relying party) a token will be issued without further authentication.
//Requires Jquery 1.9+
var hasPreAuthenticated = false;
var webAPIHtmlPage = "http://webapi.somedomain/preauth.html"
function preauthenticate() {
//ADFS breaks Ajax requests, so we pre-authenticate the first call using an iFRAME and "authentication" page to get the cookies set
return $.Deferred(function (d) {
if (hasPreAuthenticated) {
console.log("Already pre-authenticated, skipping");
//Potentially could make this into a little popup layer
//that shows we are authenticating, and allows for re-authentication if needed
var iFrame = $("<iframe></iframe>");
iFrame.attr('src', webAPIHtmlPage);
iFrame.load(function () {
hasPreAuthenticated = true;
function makeCall(){
return authenticate().then(function () {
var options = //JSONP ajaxOptions
return $.ajax(options)
view raw gistfile1.js hosted with ❤ by GitHub

Making Ajax play with Passive ADFS 2.1 (and 2.0) – Piggy-Backing

The first post, described the issue of using ADFS and Ajax to create SSO between a WebApp and a WebAPI.
This solution looks at the easiest solution, Piggy-Backing.

The central idea with Piggy-Backing is that the WebApp authenticates in the usual redirecty ADFS way and has the session cookies set.
The WebAPI then uses the same session cookie, thus not needing to ever authenticate with ADFS directly.


  • The two applications must be able to share cookies (same root domain)
  • If the WebAPI attempts to authenticate with ADFS it will error; it will error as the AJAX calls will break as per the problem description, it will also break because the redirect url after authentication will be to the WebApp not the WebAPI.

Setting up this solution is easy. Just configure the WebApp as you normally would for ADFS and then use the same config for the WebApi project i.e. set the realm to be the same as the WebApp realm.
You will also need to set the CookieHandler section of web.config to match.


If you are using subdomains and then your cookiehandler will look this in both applications web.config

 <cookieHandler requireSsl="true" domain="" /> 

Different Ports or Virtual Directories

If you are using virtual directories or differing ports such as and then your cookiehandler will look this in both applications web.config

 <cookieHandler requireSsl="true" path="/" /> 

A note on Web Farms and Microsoft Dynamics Crm 2011

If you are using load-balancing and/or MS CRM see this article. You need to implement step #3 as well to enable piggy-backing. The session cookie encryption method is changed to be more farm friendly.

Making Ajax play with Passive ADFS 2.1 (and 2.0) – The Problem

The Problem

ADFS is Microsoft’s Federated Identity Service, but if you are reading this you probably know that.
You may also know that the way it does passive authentication doesn’t work well with Ajax calls.

Below is a fiddle that shows the steps involved in authenticating a request for an ASPX page (that page belongs to the awesome Communica) protected by ADFS. This process happens the first time a request is made to an application, after that the authentication information is stored in a cookie (by default named FedAuth if you are using WIF)


Request 37 responds with Http Status code 200 (ok); the response is a payload of secret information that is submitted to the return url (your application) via javascript that submits the returned form (circled above).

This is fine when we are in a browser as the browser runs the javascript happily and submits the form. Everything is dandy. Unfortunately in an Ajax world the first Http Status of 200 is presumed to be the response and the call is never completed as intended.

This is only a problem if your application is entirely an API. If it is a mixed API/Web Application your user will be authenticated when they load the application. Any subsquent call by your application to API endpoints will already have a session and will not perform the ritual outlined above.

However, if like me, you have a 100% API based application and you are attempting to enable SSO with other applications, then there is some work to be done.

In the next posts I’ll look at 3 possible solutions:

WPF Memory Leak By Design

I have just finished debugging a memory leak in our code base. The culprit was a global static command which was rooting all controls ever attached to it, through its CanExecuteChanged event.

Surely controls which attach to this event, detach!?

No. WPF expects the ICommand.CanExecuteChanged event to apply WeakReferences for EventHandlers.
So beware if you use global commands that don’t implement this correctly.

An example of how to implement this is here.

Requery Not Suggested

During my first WPF project I noticed (like most people starting in WPF do) that DelegateCommand.CanExecute is called once and never refreshed. To force a refresh one must call RaiseCanExecuteChanged when the state of CanExecute has changed. That had a few smells about it and was cubersome, so when I stumbled across CommandManager.RequerySuggested I thought all my problems were solved.

From MSDN ”Occurs when the CommandManager detects conditions that might change the ability of a command to execute.”

All I did was create my own DelegateCommand and proxy the CanExecutedChanged event to the CommandManager.RequerySuggested event and every time WPF noticed something change it would force a refresh of my CanExecute methods. I even had the audacticity to call it BetterDelegateCommand!!

This didn’t cause too many problems on the project, as a general rule people know to keep the CanExecute logic quick and we had linear navigation in the application so there wouldn’t have been more than 10 commands bound at anyone point.

Things quickly change when you move to apps that have multiple windows/dialogs/plugins loaded and hundreds of commands can be bound. Spice that up with a developer adding CanExecute methods that do a little more than test the value of a variable and you get a significant slowdown which is very hard to debug.

Because there are times when using the RequerySuggested method is preferable Present.Commands provides the RequeryCommandDecorator and fluent method.

MyCommand = Command.Async(new SomeAction())

For everything else there is the CanExecuteChangedDecorator and fluent command. It allows you to specify an Observable which it subscribes to, when a notification comes through the CanExecuteChanged event is fired. Using an Observable adds a powerful filtering and joing tool to define when the command ‘s state has changed.

  MyCommand = Command.Async(new SomeAction())
                                .CanExecuteChangedWhen(this.WhenPropertyChanges(x => x.SomeProperty));

Everything needs a ViewModel – CollectionViewModel

CollectionViewModelThe title is a little misleading; but everyone loves generalisations and WPF. 😉
It may have been better named view-first decomposition or something similarly benign.

One of the big issues people face when implementing MVVM is collections (example, example), primarily how do I keep my model in sync. 

The reason; IMO, is that people tend to compose their ViewModels based on the models they are trying to display on-screen. Whilst this is not a bad idea (mainly because screens tend to be modelled on the models as well 🙂 ) solutions often come from a design-first approach whereby your ViewModels represent parts of the screen (not necessarily parts of the model or only a single model).

As an example take a Customer who has a collection of Addresses. When we create ViewModels based on the Model we tend to only see our objects i.e. Customer and Address. When we see a collection the first reaction is whack in a ObservableCollection.

 When creating the view that contains a collection it will often be displayed as some type of ItemsControl. The ItemsControl will often contain buttons for Adding, Deleting, Moving etc. When we look at it from the perspective of screen decomposition it becomes much clearer that there is some list component there which needs a ViewModel.

Once we come to this realisation the CollectionViewModel becomes self-evident. It’s responsibility is to maintain the underlying model; when a ViewModel is deleted from the collection it deletes the corresponding model from the underlying collection, same for add and move. I do this by listening to CollectionChanged event and providing the collection with mapping methods between ViewModel and Model.

protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)

  if (SyncIsDisabled)

            switch (e.Action)
                case NotifyCollectionChangedAction.Add:
  foreach (var item in e.NewItems)

                case NotifyCollectionChangedAction.Remove:
  foreach (var item in e.OldItems)

                case NotifyCollectionChangedAction.Reset:


So when decomposing screens or models into ViewModels; or when you encounter an issue with a design, double-check everything is a ViewModel.

MVVM Animation of ListBox – Present.Commands

Using the Present.Command decorator to change visual states after a command execution we can easily animate the addition and deletion of items in a WPF ListBox in an MVVM friendly way.
(The code is in svn for the async command samples)

Firstly, our ViewModel’s: we have an ItemViewModel representing an item in the ListBox; and an ItemCollectionViewModel representing our ListBox. Our ItemCollectionViewModel contains the two commands we are primarily focused on, Add and Delete.


  AddCommand = Command.Async
                       .Do(x => new ItemViewModel("New Item "))

Pretty self-explanatory, we create a new item, Add it to the collection and change the state of the new item viewmodel to “Add”


DeleteCommand = Command.Async
                    AsyncAction.FromDelegates<ItemViewModel, ItemViewModel>()
                        .Do(e =>
                                    e.Parameter.IsDeleting = true;
                                    return e.Parameter;
  .SuccessVisualState(ItemVisualStates.Delete, item => Remove(item))

The delete command is a little more involved. We set the Parameter (the item to delete) to “deleting” and sleep to simulate server call. Once we have deleted it on the server we play the delete animation (by changing the visual state to delete) and then once everything is finished we remove the item from the collection.

ListBox Item DataTemplate

          <!--Register the View, so it is acessible from Services, bind the current visual state so the ViewModel can control it-->
          <UniformGrid Name="grid" Style="{StaticResource DemoGrid}"  VerticalAlignment="Center" Commands:PresentVisualStateManager.GoToState="{Binding State}"
              <VisualStateGroup x:Name="ActionStates">
                <VisualState x:Name="Add"  Storyboard="{StaticResource AddAnimation}"/>
                <VisualState x:Name="Delete"  Storyboard="{StaticResource DeleteAnimation}"/>

            <Button Command="{Binding DataContext.DeleteCommand, ElementName=List}" CommandParameter="{Binding}" Height="20" Width="20">
                <Style TargetType="Button" BasedOn="{StaticResource ImageButton}">
                    <DataTrigger Binding="{Binding IsDeleting}" Value="True">
                      <Setter Property="Content">
                          <Viewbox Width="{TemplateBinding Button.Width}" Height="{TemplateBinding Button.Height}">
                            <Progress:CircularProgressBar />
                    <DataTrigger Binding="{Binding IsDeleting}" Value="False">
                      <Setter Property="Content">
                          <Image Source="{StaticResource imgMediumCross}"
                                 Width="{TemplateBinding Button.Width}"
                                 Height="{TemplateBinding Button.Height}" />

              <Label Content="{Binding Name}" />



Here we define the VisualStates Add and Delete and their corresponding animations (static resources)
We change the Button image to a circular progress bar whilst we are deleting.
We register the View with the ViewRegistry and bind to the delete command.
With a little more designer input we have a beautiful animating listbox 😉