Toolroom Tech Blog

Devlopers Digest

Windows authentication with Forms fallback in ASP

Windows authentication with Forms authentication if first one fails. Works with and MVC.

These days I was working on a simple MVC 4 application to be hosted on IIS 7.5/8, nothing special. But it made me crazy when I tried to implement the last feature ... windows authentication with forms authentication fallback. THe problem is, that IIS typically supports either Windows or Forms authentication. In principle you can do two things: a single-app solution, where both authentication methods are combined within a single application or a multi-app solution that uses one app per authentication.

How does Windows authentication work?

Windows authentication follows the NTLM/Kerberos challange handshake protocol. This is more or less, what happens:

1) User requests access to a resource

2) The server negotiates the protocol with the client

  • IIS sends two WWW-Authenticate headers: Negotiate and NTLM

3) Our negotiation comes up with NTLM authentication (Kerberos is more secure/complex, search it on your favorite search engine):

  • IIS responds with a 16-byte random challenge message
  • The client sends a hash, generated from the users password to encrypt the challenge sent by the server
  • IIS now sends user name, the original challenge, and the response from the client to the Domain Controller
  • The DC obtains the password hash for the user, and then uses this hash to encrypt the original challenge. Next, the domain controller compares the encrypted challenge with the response from the client computer. If they match, the domain controller sends the server confirmation that the user is authenticated.
  • If the credentials are ok, IIS grants access to the requested resource
  • IIS passes to ASP.NET the token that represents the authenticated user or anonymous user account. It is accessible via HttpContext.User.

Single-App Solutions

I found lots of suggestions to create a single-application solution, but mostly not worth implementing it due complexity or possible maintenance issues when moving the application to other servers.

Microsofts Paul Wilson writes on how to do it with classic on IIS 6. His solution builds up on forms authentication and requires two login pages and a custom 401 page. But on the one hand i do not want no modify the application too much andf on the other hand it's hard to make it work on IIS7.

So, I decided to use a multi-application approach that indeed needs a second application but is much smarter and cleaner in my opinion.

Multi-App Solution

As already said, you can only use either windows or forms authentication in a application. And this is exactly the way this solution is based on.


  • No modification or optimization of your base application
  • Use only standard authentication modules
  • Attach this solution to any forms application


  • Requires a second application or at least a sub-application on IIS

Implementation Summary

First of all we need our base web application providing configured to use forms authentication. Then we need another, almost empty web application, that is configured to use Windows Authentication. The latter is responsible to do the Windows Authentication and to set the forms authentication cookie before it redirects to our base web application. If the windows authentication did not work, HttpContext.User.Identity.IsAuthenticated is set to false and the user will be redirected to the forms login page.

How to do it uses a so called machine key for ViewState encryption and validation as well for signing the authentication ticket for forms authentication. This feature was introduced especially for load balancing. That means, if both of our applications, the base and the authentication app, use the same key, they can both access the authentication cookie.

In our authentication app we just need one Action, I create the action 'Index' within a controller named 'NtlmController'. Since the Windows authentication of the request is already done before the action is executed, we can  access the authentication token here. If the token says, the user is authenticated, we set the authentication cookie and that's it.

public ActionResult Index()
	var principal = (IPrincipal) Thread.CurrentPrincipal;
	if (principal != null) {
		if (!principal.Identity.IsAuthenticated)
			throw new ArgumentException("Principal is not authenticated, should not happen :)");
		//User is validated, so let's set the authentication cookie
		FormsAuthentication.SetAuthCookie(principal.Identity.Name, true);

	//use this if your authentication app is a sub-app of your base app
	//return Redirect("~/../");

	//use this if your authentication app is another app on the server
	return Redirect("");

Now generate a machine key for the authentication app. In IIS >=7 it's easy to achieve this: In IIS left click on your app, in the features view open machine key and click generate keys. Save it and IIS will update your web.config automatically.


The resulting line should look like this:

	<machineKey decryptionKey="C7976FD237C42579DDD645F4649DD05A3F09F32069691C34" validation="SHA1" validationKey="1EE24CF0741E7F7557E5390CCEF5F5DF1BF90F098294AF2BC3D8B3C2F1195E2E268377FDD7361AE8998374064A6CB23DE361414DDDDA90DF49D4BC6E55687F63" />

Now let's do the only modifications to our base app. First copy the machineKey line to to the web.config and add some parameters to the forms authentication configuration, so that redirects between both applications are allowed:

	<machineKey decryptionKey="C7976FD237C42579DDD645F4649DD05A3F09F32069691C34" validation="SHA1" validationKey="1EE24CF0741E7F7557E5390CCEF5F5DF1BF90F098294AF2BC3D8B3C2F1195E2E268377FDD7361AE8998374064A6CB23DE361414DDDDA90DF49D4BC6E55687F63" />
	<authentication mode="Forms">
		<forms loginUrl="/Account/Login" timeout="2880" domain="localhost" path="/" enableCrossAppRedirects="true" name=".ASPXFORMSAUTH" protection="All" />

That's it. If you directly access your base app, you'll get your forms login. But if you access the authentication app from a machine within your domain, you will automatically be logged on.

Good luck.



Furher information

Microsoft Word 2013: PDF Flow

New Word 2013 opens PDF files :)

Today I unintentionally found the probably best feature in Word 2013: PDF Reflow. In Terms of Microsoft this means: Open a PDF in Word, and its paragraphs, lists, tables, and other content act just like Word content.

And it works! :)


Objective-C versus C# Syntax

A few major differences between C# and Objective-C

You are .net developer and think about starting iDevice development? Ok, have fun ... It's different. It's nearly impossible to show all differences between C# and Objective-C. I will just provide you with a very few important things to know. 

  • Basically, Objective-C is unmanaged, so the developer is responsible for memory management. Why basically? There is a garbage collector is available since 2010, but not for older versions of OS X and iOS and it seems the GC dramatically decreases the app performance.
  • Objective-C is a superset of C, therefore it requires a header file 'LotteryEntry.h' (aka interface file) to declare variables and methods. Those methods are then implemented in the implementation file 'LotteryEntry.m'. 
  • The syntax is in the style of Smalltalk... 
  • OC has no properties like C#, instead apple has a accessor guidlance. I.e. to provide accessors for the variable firstNumber, we need to provide a get-method called firstNumber and a set-method called setFirstNumber.
  • The Cocoa API is very simple and easy. It is really not what we can call voluminous.

In the following example I will create a simple .NET class with two properties and one overridden method. Then, to give you an idea how Objective-C Looks like, I'll show the same class translated to Objective-C.

Due to the smalltalk syntax, Objective-C looks crazy for C# or Java developers. But here a few things to know before you start reading the code.




- (NSString *)getString:(NSString *)myString
    return myString;
public string GetMyString(string myString)
    return myString;
[self getString:anyDefinedString];
NSDate *now = [[NSDate alloc] init];
var now = new DateTime();


using System;

namespace Dweedo.Web.Common
    public class LotteryEntry
        readonly Random _rand = new Random();

        public LotteryEntry(DateTime? entryDate = null)
            EntryDate = entryDate jQuery15203358672992216089_1349763670826 DateTime.Now;

            FirstNumber = _rand.Next(1, 101);
            SecondNumber = _rand.Next(1, 101);

        public int FirstNumber { get; private set; }

        public int SecondNumber { get; private set; }

        public DateTime EntryDate { get; set; }

        public override string ToString()
            return string.Format("{0} = {1} and {2}",



#import <Foundation/Foundation.h>

@interface LotteryEntry : NSObject {
    NSDate *entryDate;
    int firstNumber;
    int secondNumber;

- (id)initWithEntryDate:(NSDate *)date;
- (void)setEntryDate:(NSDate *)date;
- (NSDate *)entryDate;
- (int)firstNumber;
- (int)secondNumber;



#import "LotteryEntry.h"

@implementation LotteryEntry

- (id)init{
    return [self initWithEntryDate:[NSDate date]];

- (id)initWithEntryDate:(NSDate *)date{
    if(![super init]) return nil;
    [self setEntryDate:date];
    firstNumber = random() % 100 +1;
    secondNumber = random() % 100 +1;
    return self;

- (void)setEntryDate:(NSDate *)date{
    entryDate = date;

- (NSDate *)entryDate{
    return entryDate;

- (int)firstNumber{
    return firstNumber;

- (int)secondNumber{
    return secondNumber;

- (NSString *)description{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    return [[NSString alloc] initWithFormat:@"%@ = %d and %d",
              [dateFormatter stringFromDate:entryDate],