Some users still live in era of Windows 95 where you had to do double-click to make something happen. And this double-clicking goes with them when they go online. So they double-click on links, double click on submit buttons… Wait? did you just double-clicked that button? submitted the form twice? OOPS!

There are a lot of advice online how to stop this happening, but I have not found a complete solution. Here is my stub at this (using jQuery):

$('input:submit').click(function () {
    var $button = $(this)[0];
    var oldValue = $button.value;
    setTimeout(function() {
        $button.disabled = true;
        $button.value = 'Working...';
        setTimeout(function() {
            $button.disabled = false;
            $button.value = oldValue;
        }, 500);
    }, 0);
});

What are we doing here? seems like too much code for a simple task. A lot of advice goes to e.preventDefault() but that stops the form submission. Some people recommend adding form.submit() after the preventing default action. That smells. What if I did not want to submit the form, but some other event was triggered on click? If you just disable the button on click – your form will not be submitted because disabled html elements are not submitted.

In this snippet I’m delaying button disabling. This gives a chance to other events to fire – I don’t need to submit the form manually. And inside that timeout I’m setting another delayed function to re-activate the function. Because in era where JavaScript is executed on servers (node.js, I’m looking at you!), it is just plain wrong not to do a validation on a client. So in case when the validation has failed, I re-enable the button again so user can re-submit.

I’ve tried that in latest (17 Dec 2014) Chrome and in IE9 in both cases works as expected. Let me know how this can be improved!

I’m a frequent user of RDP and sometimes you get stuck with within the same connection window and can’t get unstuck because the bar on top just does not come up. To make the bar come-down hit CTRL + ALT + HOME and to break free from the full-screen mode hit CTRL + ALT + BREAK

I’ll leave this here for my future reference.

The title is quite vague, but this is the best I can call this post. Bear with me, I’ll explain what I mean.

While working with Asp.Net MVC, in Razor views I use Html helpers a lot. My view end up looking like this:

@Html.TextBoxFor(m => m.Title)
@Html.TextAreaFor(m => m.Description)

And later if I write JavaScript and need to reference one of the input fields, I usually do this:

var title = document.getElementById("Title");
var description = document.getElementById("Description");

or if you use jQuery you go like this:

var title = $("#Title");
var description = $("#Description");

This is fine and works. Until you start renaming field names in your model. And then you need to track down where you hard-coded the input id. And many times these references slip away (they do from me!) and remain unchanged.

Would it not be great if these changed could be picked up automatically? or even better, do some sort of strongly-typed reference to the element if it is used in JavaScript?

Just use @Html.IdFor(m => m.Name)

And your JS code would look like this:

var title = document.getElementById("@Html.IdFor(m => m.Title)");
var description = $("#@Html.IdFor(m => m.Description)");

Below I’ve re-invented the wheel. [Facepalm]

So I trolled through MVC source code and figured out how it generates id’s for elements and here are my findings:

using System;
using System.Linq.Expressions;
using System.Web.Mvc;

public static class HtmlHelpers
{
    public static String ElementId<T, TResult>(this HtmlHelper<T> htmlHelper, Expression<Func<T, TResult>> selector)
    {
        var text = System.Web.Mvc.ExpressionHelper.GetExpressionText(selector);
        var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(text);
        var id = TagBuilder.CreateSanitizedId(fullName);

        return id;
    }
}

As you can see, I have not made any custom code, all components are from MVC and are applied in the same order as MVC does when it generates id for elements when you call for @Html.EditorFor(). So this guarantees the provided id from this function will match the id in your form.

In the view you use it like this:

@Html.ElementId(m => m.Title)

And your JS code would look like this:

var title = document.getElementById("@Html.ElementId(m => m.Title)");
var description = document.getElementById("@Html.ElementId(m => m.Description)");

A bit of mouthful, but gives you the safety net of strong types. I have not actually used it widely, so not sure how it’ll work out in the longer run.

A note to myself, next time I try to do view compilation in msbulid and see exception

Can’t find the valid AspnetCompilerPath

I should either install VS2013 on my build server. Or choose a different version of msbuild.exe:
C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild.exe.

The problem is caused by version mis-match. New msbuild is part of Visual Studio 2013 and not part of .Net framework itself. And by default your PATH variable points to .Net folders where older msbuild is found. So you in your scripts you need to explicitly specify what msbuild you need to use.

Part 1: AspNet Identity and IoC Container Registration

Sounds like I’m making a series of articles about ASP.Net Identity and how to use it with Depenency Injection. Part 1 have seen a lot of hits from Google in just a few days. I suppose it is worth extending the tutorial.

Building up on Part 1 where I wired all Identity components to be injected by Unity container, now I’m going to add emailing service for email confirmation and password reset.

My plan is to use SendGrid as a email service and email debugging service Mailtrap.IO as a hosted fake SMTP server.

EmailService Class

Standard VS template for ApplicationUserManager does not have an implementation for EmailService:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        return Task.FromResult(0);
    }
}

Let’s create one that uses SendGrid to send emails. Go to http://sendgrid.com/ and get registered: there is a free tier that allows you to send up to 200 emails a day. This is good enough for our testing. Make sure you put your details correctly – all accounts go through moderation before they are allowed to send out emails. And it took a few hours before my account got approved, I also had to reply their support saying that I’m a developer and will only use the account for testing and learning purposes.

Now go install SendGrid nuget package:

PM> Install-Package SendGrid 

Now take a careful look on IIdentityMessageService interface: it has only one method: Task SendAsync(IdentityMessage message). So what information does IdentityMessage contains?
By looking in decompiler I see this:

Identity Message

Basically it is a data container with no methods. We have strings available:

  • Destination – contains email address
  • Subject – email subject
  • Body – text of the email

Now let’s look on SendGrid documentation for C# client. I came up with this as an implementation for the email service:

using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using SendGrid;


namespace IoCIdentity.Identity
{
    public class SendGridEmailService : IIdentityMessageService
    {
        public async Task SendAsync(IdentityMessage message)
        {
            // Create the email object first, then add the properties.
            var myMessage = new SendGridMessage();

            // this defines email and name of the sender
            myMessage.From = new MailAddress("no-reply@tech.trailmax.info", "My Awesome Admin");

            // set where we are sending the email
            myMessage.AddTo(message.Destination);

            myMessage.Subject = message.Subject;

            // make sure all your messages are formatted as HTML
            myMessage.Html = message.Body;

            // Create credentials, specifying your SendGrid username and password.
            var credentials = new NetworkCredential("SendGrid_Username", "SendGrid_Password");

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);

            // Send the email.
            await transportWeb.DeliverAsync(myMessage);
        }
    }
}

I’ve renamed EmailService into SendGridEmailService because we are going to have 2 services: one for production, another for testing.

Now it is a time to register this service with DI Container. Open our old friend UnityConfig and add the following line:

// whenever object requires IIdentityMessageService dependency, give them SendGridEmailService
container.RegisterType<IIdentityMessageService, SendGridEmailService>();

Inject this service into ApplicationUserManager:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store, IIdentityMessageService emailService) : base(store)
    {
        this.EmailService = emailService;
        // the rest of configuration
    }
}

Change AccountController to send out email confirmations on user registration:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await signInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                string code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await userManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

All of this is unmodified template code. All I had to do is to uncomment 3 lines related to userManager.SendEmailAsync() and make sure names match.

And now it is a time to test! Hit F5 to start debugging your site, this should launch your web-application. Go to register page, fill in your email, put a password and watch magic. Once you’ve done the registration, you should receive email from your own service! But beware, I got my confirmation email going to spam box in Gmail. Oops!

Check your spam inbox!

Click on link in the email and this should bring you back to your site to email confirmation page /Account/ConfirmEmail.

Now you can stop there: you have your email confirmation sent out and email service class is injected. But the fun only starts!

Fake SMTP Server

When testing account registration, and if you send emails to your real inboxes, you will run out of addresses pretty fast. I’ve got like 5 accounts, but I’d like to try registration process many more times than that. Also I don’t want to worry about sending an email to a real email address, in case I send it to somebody else, not just myself (I’ve done it in the past!).

I have written about Mailtrap.io before and this is another chance to mention this awesome service and how to hook it into your development cycle.

What is Mailtrap.io

Mailtrap is a fake SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming real customers.

I think this sums up pretty well. I’ll add that there is a pile of fake SMTP servers you can install locally. But I have not seen hosted solutions (other than Mailtrap). When working ina team, centralised, install-free and configuration-free solution works best. Think of a new developer in the team – he/she gets a source code from your version control, hit F5 and up and running with the project. No need to configure fake SMTP server locally.

Now head to Mailtrap.io and get registered. There is a free tier that is just perfect for our small experiment (don’t you love the free tiers in services?).

Anyway, enough blah, more code!

To use Mailtrap service, we need to implement IIdentityMessageService. Mailtrap is quite good with documentation and it already provides a “hello world” sample on many programming languages, including C#:

Hello World for Mailtrap

I’ll use that code as a starting point for our implementation:

using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;


namespace IoCIdentity.Identity
{
    public class MailtrapEmailService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
        var client = new SmtpClient
        {
            Host = "mailtrap.io",
            Port = 2525,
            Credentials = new NetworkCredential("24077a300d1d0a919", "36ac3619e3c015"),
            EnableSsl = true,
        };

        var @from = new MailAddress("no-reply@tech.trailmax.info", "My Awesome Admin");
        var to = new MailAddress(message.Destination);

        var mail = new MailMessage(@from, to)
        {
            Subject = message.Subject,
            Body = message.Body,
            IsBodyHtml = true,
        };

        client.Send(mail);

        return Task.FromResult(0);
        }
    }
}

To try it out, I’ll replace what type Unity is injecting as IIdentityMessageService:
Previous line container.RegisterType<IIdentityMessageService, SendGridEmailService>();
Now becomes container.RegisterType<IIdentityMessageService, MailtrapEmailService>();

Start the application and try to register the user: watch your Mailtrap inbox receive first intercepted email:

Send to what email address???

That is pretty cool. You can give a random email address on the registration and only you will see the email, it won’t go anywhere further than the fake inbox. There is an option to redirect all incoming fake emails, but I have not found the use case for this yet.

Inject Different Classes in Dev and Prod

Now we have 2 different implementations of email service that can be used in Identity Framework. I would like to configure our DI container to use the implementation most appropriate to the case. If we are in production, use SendgridEmailService. If we are testing or developing use MailtrapUserService.

I find the problem of deciding if we are in production or in testing pretty hard. Given that code on developers machines are usually executed in Debug mode, we can easily check for that. But when it comes to Testing environment, it is usually used by QA people (or sometimes clients) and is not running in Debug mode. Ideally Testing environment is identical to production, so there is not many “in-code flags” that we can use.
In the past I have added a setting in web.config/appSettings: <add key="isProduction" value="false" /> and checked for this setting. For production, this setting was changed during the deployment pipeline (web.config transformation).

But for the purposes of our little tutorial, we can rely on checking if the code is in Debug mode or if the request is local to the server where it is hosted. Here is the registration part:

container.RegisterType<IIdentityMessageService, SendGridEmailService>("production");
container.RegisterType<IIdentityMessageService, MailtrapEmailService>("debugging");

container.RegisterType<IIdentityMessageService>(new InjectionFactory(c =>
    {
        try
        {
            // not in debug mode and not local request => we are in production
            if (!HttpContext.Current.IsDebuggingEnabled && !HttpContext.Current.Request.IsLocal)
            {
                return c.Resolve<IIdentityMessageService>("production");
            }
        }
        catch (Exception)
        {
            // Catching exceptions for cases if there is no Http request available
        }
        return c.Resolve<IIdentityMessageService>("debugging");
    }));

Now this looks scary. Let’s talk through each bit separately. This line:

container.RegisterType<IIdentityMessageService, SendGridEmailService>("production");

is telling the container to register type SendGridEmailService as an implementation for interface IIdentityMessageService and add named key to this registration as “production”. Pretty much the same happens on the next line about MailtrapEmailService, only the registration key is “debugging”. Basically this is some sort of alias for the registration. This works for the cases when we have more than one implementation class registered for one interface, just as we have at the moment.

Registration for IIdentityMessageService with InjectionFactory is the place where we decide which of the implementations to go for. I check if we are running not in debug and http request is not local, then it is production code and we need SendgridEmailService, otherwise we need MailtrapEmailService. I do wrap checking for conditions into try/catch block: Http.Current will throw exceptions in cases when no http request is available (this can happen if you for some reason try to execute this code in Application_Start()).

I do resolution of concrete implementations through container and named resolution:

return c.Resolve<IIdentityMessageService>("production");

This call matches provided key "production" to previous registrations for the requested interface IIdentityMessageService with this key, and SendgridEmailService should be resolved.

Instead of named resolutions I could have created concrete classes:

return new SendgridEmailService();

But if these classes evolve and dependencies are introduced (e.g. ILoggingService is injected), we will need to go back to this code and add dependencies. If we do resolution from the container, it will take care of the dependencies, as long as they are all registered.

Resetting Password Through Email

So far I’ve been getting an email only on user registration. But I could not reset the password. Let’s fix this to complete our solution.

AccountController already has all the stuff required for password resetting. All you need to do is uncomment some code:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await userManager.FindByNameAsync(model.Email);
        if (user == null || !(await userManager.IsEmailConfirmedAsync(user.Id)))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return View("ForgotPasswordConfirmation");
        }

        // Send an email with this link
        var code = await userManager.GeneratePasswordResetTokenAsync(user.Id);
        var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
        await userManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
        return RedirectToAction("ForgotPasswordConfirmation", "Account");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And add the link to this action from login page Login.cshtml:

<p>
    @Html.ActionLink("Reset password", "ForgotPassword")
</p>

That’s it – go try reset your password for the accounts you already created – all password reset passwords should go through to Mailtrap.

Give Me The Codez!

Here is the the full source code based on Part 1 and added code above

P.S. I’m struggling what should the next article in the series should be. I’m thinking 2FA and send out SMS, but there won’t be much DI happening there? Please suggest in comments.

I’m reading a lot of blogs about development and .Net. One of the blogs I read is from Jimmy Bogard and one of the recent posts there is about guidelines for using Dependency Injection container.

I got involved in comments and one of the commenters was suggesting using Func<IFoo> as injection instead of injecting the instance for IFoo. And reasons for that were:

  1. The “captive dependency” problem… objects with more constrained lifetime being held by objects with longer->lived lifetime.

  2. The (wasteful) big-bang object graph problem… when an MVC action only requires 1 dependency, but the dependency graph for all dependencies within the controller need to be resolved.

  3. The occasional property injection… when its 2am and I don’t feel like fixing a circular dependency issue (don’t hate).

And a follow up comment:

If you have circular dependencies, you aren’t immediately evaluating the circular path

I’d like to address this first, as it bothers me very much myself. It is best recommended to avoid circular dependency and it is entirely possible (I have not yet came across the situation where code could not be refactored out of that). In classical DI you’d fix circular dependency with property injection. Let’s try to fix this problem with injection of a function.

Here is a simple situation with classes:

public interface IBar
{
    void DoBar();
}

public class Bar : IBar
{
    private readonly Func<IFoo> fooFunc;

    public Bar(Func<IFoo> fooFunc)
    {
        this.fooFunc = fooFunc;
    }


    public void DoBar()
    {
        var foo = fooFunc.Invoke();
        foo.DoFoo();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Bar.DoBar");
    }
}

And Foo class:

public interface IFoo
{
    void DoFoo();
}

public class Foo : IFoo
{
    private readonly Func<IBar> barFunc;

    public Foo(Func<IBar> barFunc)
    {
        this.barFunc = barFunc;
    }


    public void DoFoo()
    {
        var bar = barFunc.Invoke();
        bar.DoBar();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Foo.DoFoo");
    }
}

Foo depends on IBar and Bar depends on IFoo. Simple circular dependency with proposed injection of functions that resolve actual class entities.

Let’s see how we can create instance of Foo and instance of Bar

Func<IBar> barFunc = () => new Bar(???);

Func<IFoo> fooFunc = () => new Foo(barFunc);

We still have circular dependency, because we can’t create a function to resolve IBar without function that resolves IFoo first.

Ok, so no what? Let’s try to have one of the objects depend on function and another on an interface:

public class Bar : IBar
{
    private readonly IFoo foo;

    public Bar(IFoo foo)
    {
        this.foo = foo;
    }


    public void DoBar()
    {
        foo.DoFoo();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Bar.DoBar");
    }
}

And Foo class is unchanged. And try to resolve both of the objects:

Func<IBar> barFunc = () => new Bar(new Foo(???));

Func<IFoo> fooFunc = () => new Foo(barFunc);

We still are in the same situation. We can’t resolve new instance of Bar because we can’t have Foo.

Another attempt – let’s do property injection:

public class Bar : IBar
{
    public Func<IFoo> FooFunc { get; set; }

    public Bar()
    {
    }

    public void DoBar()
    {
        var foo = FooFunc.Invoke();
        foo.DoFoo();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Bar.DoBar");
    }
}

Now we are talking:

Func<IBar> barFunc = () => new Bar();

Func<IFoo> fooFunc = () => new Foo(barFunc);

var foo = fooFunc.Invoke();
var bar = new Bar()
                {
                    FooFunc = fooFunc,
                };

bar.DoBar();

The only problem that we still have circular dependency, only run-time, rather than compile time. See if you can figure out why it happens (just try running the code)! I’ve created a gist with full code I’ve tried running. Functions are unwrapped from lambdas, so you can set breakpoints and step into them while debugging.


Now, see if you notice a great big deception I’ve given you here. The dependency is very circular on functional level: DoBar() calls DoFoo() calls DoBar() calls DoFoo(), etc. It is impossible to run these functions: it is an infinite recursion/loop/whatever. And not type of wiring up will help you out. You’ll need to remove one of the function invocations from the classes:

public void DoFoo()
{
    Thread.Sleep(1000);
    Console.WriteLine("Executing Foo.DoFoo");
}

Now you can run the sample and it won’t explode with a series of exceptions. But our object wiring looks complex and is not much different from direct injection coupled with property injection of an object:

public class Bar : IBar
{
    public IFoo Foo { get; set; }

    public Bar()
    {
    }

    public void DoBar()
    {
        if (Foo == null)
        {
            throw new Exception("Foo property is not populated");
        }

        Foo.DoFoo();

        Console.WriteLine("Executing Foo.DoFoo");
    }
}


public class Foo : IFoo
{
    private readonly IBar bar;

    public Foo(IBar bar)
    {
        this.bar = bar;
    }

    public void DoFoo()
    {
        Thread.Sleep(1000);
        Console.WriteLine("Executing Foo.DoFoo");
    }
}

Wiring up and execution looks like this:

var bar = new Bar();
var foo = new Foo(bar);
bar.Foo = foo;

foo.DoFoo();
bar.DoBar();

The second version looks much more simple than the version with functions

Containers and function injection

In the same discussion I said that containers are not geared toward injection of functions. Well, yes, you can totally do this (Autofac):

var builder = new ContainerBuilder();
Func<IBar> barFunc = () => new Bar();

builder.RegisterInstance(barFunc);
builder.RegisterType<Foo>().As<IFoo>();
var container = builder.Build();

var foo = container.Resolve<IFoo>();
foo.DoFoo();

And it will work (given that Foo constructor takes Func<IBar>). But with given registration you can’t resolve Bar because it is not registered – we only registered Func<IBar>, but not IBar.

And I’m not aware of the way to register Func<IBar> together with IBar in one go, making it double-effort. Also imagine I have hundreds on ICommandHandler<TCommand> classes and hundreds of IQueryHandler<TQuery, TResult>. How can you register that with functions? Add a few decorators on top of that.

Probably one can come up with clever methods to do it, but that’ll be an addition to containers, not built-in functionality. And this is what I called “containers are not geared towards”.

Conclusion

However interesting this idea might seem like, I’ll stick to the classical DI with classes depending on interfaces. And all the issues discussed can be avoided by mostly following SOLID principles; no circular dependency; no massive graphs of objects; object resolution should be cheap and simple. To avoid captive dependency use Decoraptors.

Warning: If you have no idea what Dependency Injection is or you don’t know why you need this, don’t waste your time on this article. This approach is not recommended for cases when you don’t need a IoC container and have only a handful of controllers. Visual Studio 2013 template with Identity framework installed works perfectly out of the box. You’ll need minor changes to controllers and implement your EmailService, but you don’t need DI to enjoy full power of Asp.Net Identity framework. This article does not explain what DI is, how it works and why you need it. So proceed with caution and only if you know the difference between constructor injection and lifetime scope.

TL;DR: Registration code for Autofac, for SimpleInjector, for Unity.

Part 2: Sending Emails in Asp.Net Identity using Dependency Injection, Sendgrid and debugging it with Mailtrap.io

I regularly monitor StackOverflow for questions related to AspNet Identity framework. And one question keeps popping up over and over again: how do you use Inversion of Control containers with this framework.

If you know the main principles of Dependency Injection, things are very simple. Identity is very DI-friendly and I’ve done a number of projects with Identity and injected all Identity components via Autofac or SimpleInjector. The principles behind DI are applicable to all the containers, despite the differences in API’s for registration.

For the sake of this blog-post I’ll start with the standard VS2013 template and use Unity container, just because I’ve never used Unity before. You can view registrations for SimpleInjector in my test-project.

Projects where I used Autofac are far too complex to show as an example and none of them are open-source, so Autofac fans will have to figure out themselves from my examples.

Create project, install dependencies

For this sample I’ve used standard MVC project template from Visual Studio 2013.

First thing I’ve done – updated all Nuget packages. Just to keep new project really up to date.

Next thing I do is install container nuget packages:

PM> Install-Package Unity.Mvc 

In default template I don’t like the way Identity classes are all in one file and in App_Start folder, so I move them to /Identity folder and place a separate classes into separate folders. This is my preference, not really a requirement -) (Did you know with Reshrper you can place caret on class name and Ctr+R+O -> Move To Folder and get all the classes into separate files, into different folder)

Configure DI

Now, once we have installed Unity, let’s register components with it. I see that Unity nuget package have created 2 files for me in /App_Start: UnityConfig.cs and UnityMvcActivator.cs.

UnityConfig.cs looks like this (I’ve removed comments):

public class UnityConfig
{
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
        // TODO: Register your types here
        // container.RegisterType<IProductRepository, ProductRepository>();
    }
}

This is pretty standard class most containers have for registration, but I’ve never seen Lazy initialisation of the container before. I’ll keep it that way – when in Rome, do as Romans -) However I’ve got strong feeling that RegisterType method should be private, as it makes no sense to expose it to the world. And here the registrations of components should go. I’ll come back to this class later.

Now I’d like to have a look on another unity class UnityWebActivator:

using System.Linq;
using System.Web.Mvc;
using IoCIdentity;
using Microsoft.Practices.Unity.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnityWebActivator), "Shutdown")]

namespace IoCIdentity
{
    public static class UnityWebActivator
    {
        public static void Start() 
        {
            var container = UnityConfig.GetConfiguredContainer();

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }

        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
    }
}

I’ve included namespaces and attribute, as these are pretty important here. The two assembly attributes come from WebActivator project and tells the application to execute methods before application starts and on application shut-down.

Start() method calls to the GetConfiguredContainer() from UnityConfig class that we’ve seen earlier – this is just initiates the DI container with registered types.
Next two lines de-register standard MVC filter instead registers Unity filter provider. I presume this is to enable injections into filter objects.

This line

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

Sets Unity container as MVC standard dependency resolver, so in your static methods you can go DependencyResolver.Current.GetService<MyService>(); and this way Unity will be called into action and will resolve an instance of type MyService.

I think this is good enough initialisation code. Let’s move on.

Register components

Now let’s register components we need. Despite the fact, that Unity can resolve concrete types without registration (as per comments I’ve deleted), I’ll register them anyway. Here is the basic list of registrations I have. This is not a complete list, I’ll add more types there when I need them:

private static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<ApplicationDbContext>();
    container.RegisterType<ApplicationSignInManager>();
    container.RegisterType<ApplicationUserManager>();
}

Now, lets look on end consumers of our components – controllers. I’m starting with AccountController as it has a use of UserManager and ApplicationSignInManager. By default it looks like this:

public class AccountController : Controller
{
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    private ApplicationSignInManager _signInManager;

    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set { _signInManager = value; }
    }


    // this is hidden on the very bottom - go find it and delete later
    private IAuthenticationManager AuthenticationManager
    {
        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }



// list of actions

Let’s follow the DI principles and remove all the crap. HttpContext.GetOwinContext().Get<ApplicationUserManager>() is a prime example of service locator as an anti-pattern. Also this does not use our Unity container, this uses Owin for object resolution. We don’t want to mix Owin registrations with Unity registrations for many reasons (the biggest reason is lack of lifetime management between 2 containers). So now my AccountController looks like this:

private readonly ApplicationUserManager userManager;
private readonly ApplicationSignInManager signInManager;
private readonly IAuthenticationManager authenticationManager;

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, IAuthenticationManager authenticationManager)
{
    this.userManager = userManager;
    this.signInManager = signInManager;
    this.authenticationManager = authenticationManager;
}

// actions

If you noticed, previously we have not registered IAuthenticationManager with the container. Let’s do this now:

container.RegisterType<IAuthenticationManager>(
    new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

If you run your application now, you’ll get exception that “IUserStore can’t be constructed” – that is correct, we have not registered it anywhere and it is required for ApplicationUserManager. Register now IUserStore:

container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
            new InjectionConstructor(typeof(ApplicationDbContext)));

I specify what type I’d like to use as a parameter, otherwise Unity will try to resolve DbContext which is wrong. But instead we need our ApplicationDbContext.

ApplicationUserManager class

Now let’s look on UserManager class. The constructor does not have much in it, only takes IUserManager. But there is static method Create that creates an instance of UserManager and configures the settings:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    // configuration stuff here
}

This method creates instances of ApplicationUserManager. Let’s copy all the code from Create method into constructor:

public ApplicationUserManager(IUserStore<ApplicationUser> store, IdentityFactoryOptions<ApplicationUserManager> options)
        : base(store)
    {
        // Configure validation logic for usernames
        this.UserValidator = new UserValidator<ApplicationUser>(this)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        this.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };

        // Configure user lockout defaults
        this.UserLockoutEnabledByDefault = true;
        this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        this.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        this.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        this.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        this.EmailService = new EmailService();
        this.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;

        if (dataProtectionProvider != null)
        {
            this.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
    }

Now we have constructor parameter IdentityFactoryOptions<ApplicationUserManager> options. Previously this was supplied by Owin when we executed this code:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

This GetUserManager does magic tricks (I tried following their source code, but I’m not brainy enough-) and adds parameter you see above. But we’d like to avoid registration through Owin.

IdentityFactoryOptions<ApplicationUserManager> provides IDataProtectionProvider needed to generate user tokens to confirm account registration and for password reset tokens. It is used in constructor like this:

var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
    IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");

    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
}

We can’t resolve ourselves IdentityFactoryOptions, we need Owin for that. And we can’t resolve IDataProtector ourselves as well. But after looking on source code of Owin I have found where this dataProtector is coming from: IAppBuilder.GetDataProtectionProvider(). But IAppBuilder is not available anywhere apart from Startup.Auth.cs file. So we can resolve this class where we can and save as static reference. And then use this reference where needed:

public partial class Startup
{
    // add this static variable
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        // add this assignment
        DataProtectionProvider = app.GetDataProtectionProvider();

        // other stuff goes here unchanged
    }
}

and in ApplicationUserManager I rewrite part with assigning UserTokenProvider like this:

// here we reuse the earlier assigned static variable instead of 
var dataProtectionProvider = Startup.DataProtectionProvider;

// this is unchanged
if (dataProtectionProvider != null)
{
    IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");

    this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
}

Now we can remove dependency of IdentityFactoryOptions<ApplicationUserManager> from ApplicationUserManager constructor. And the whole class now looks like this:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
    {
        // Configure validation logic for usernames
        this.UserValidator = new UserValidator<ApplicationUser>(this)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        this.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };

        // Configure user lockout defaults
        this.UserLockoutEnabledByDefault = true;
        this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        this.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        this.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        this.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        this.EmailService = new EmailService();
        this.SmsService = new SmsService();

        var dataProtectionProvider = Startup.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");

            this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
        }
    }
}

At this point the application should be usable and you should be able to register as a user, login and log out.

Clean-Up

Now that our app works with DI, let’s clean up some static calls that we don’t want around.

First of all, let’s fix ManageController, remove all empty controllers and initialisation of UserManager from OwinContext. The constructor should look like this:

private readonly ApplicationUserManager userManager;
private readonly IAuthenticationManager authenticationManager;

public ManageController(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
{
    this.userManager = userManager;
    this.authenticationManager = authenticationManager;
}

Now let’s go into Startup.Auth.cs and look on bits we don’t want:

// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

I for sure know that Identity resolves ApplicationUserManager through Owin context and it uses it in certain cases. All the other Owin-resolved objects can be removed from this list:

// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

Then remove static object creation for UserManager and SignInManager to Unity resolution:

app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

And remove static methods ApplicationUserManager.Create and ApplicationSignInManager.Create – no longer needed or used anywhere.

By now you should have all Identity components injected into your controllers via Unity container. I was able to register and login into the application. So the goal of this article is complete.

For your reference full source code of the solution is available on GitHub

One other reader did send yet another interesting question. The conversation started about AspNet Identity, but the question is actually about Owin and how it works.

See this bit of code from HttpContextBaseExtensions

public static IOwinContext GetOwinContext(this HttpContextBase context)
{
    IDictionary<string, object> environment = GetOwinEnvironment(context);

    if (environment == null)
    {
        throw new InvalidOperationException(
            Microsoft.Owin.Host.SystemWeb.Resources.HttpContext_OwinEnvironmentNotFound);
    }

    return new OwinContext(environment);
}

And the question goes like this:

As you can see, each time the OwinContext is pulled from the HttpContext, it returns a new context…. For an object that is named Context I found this rather strange behaviour. It also raises my eyebrows when I think of the term ‘CreatePerOwinContext’. What does this mean, when a new context is created every time. If you put this in a DI perspective, transient should be the name.

Let’s start from first part of the question.

Owin is all about dictionary. If you look on implementation of ApplicationBuilder, there are 2 dictionaries of objects and a list of middlewares:

private readonly IList<Tuple<Type, Delegate, object[]>> _middleware;
private readonly IDictionary<Tuple<Type, Type>, Delegate> _conversions;
private readonly IDictionary<string, object> _properties;

That’s a bit of a mouthful. Simple one is _conversion – this is a collection of rules how you can go from one type to another type: identified by Tuple with FromType and ToType and an actual delegate which does the conversion. Dictionary named _middleware is a list middleware objects with set of parameters – I’m not going to touch it here, as it is a magical unicorn I know nothing about.

If you look on HttpContextExtensions again, to create OwinContext the code queries dictionary HttpContext.Items with Owin key. HttpContext.Items is used “to organize and share data between an IHttpModule interface and an IHttpHandler interface during an HTTP request”.

Then reference to the object stored in HttpContext.Items is passed into constructor of OwinContext where the same reference to the dictionary is passed into OwinRequest and OwinResponse objects:

public OwinContext(IDictionary<string, object> environment)
{
    if (environment == null)
    {
        throw new ArgumentNullException("environment");
    }

    Environment = environment;
    Request = new OwinRequest(environment);
    Response = new OwinResponse(environment);
}

OwinRequest and OwinResponse are convenient wrappers to access objects from Environment dictionary. You’ll see a lot of methods like this in the above classes:

    /// <summary>
    /// Gets or set the HTTP method.
    /// </summary>
    /// <returns>The HTTP method.</returns>
    public virtual string Method
    {
        get { return Get<string>("owin.RequestMethod"); }
        set { Set("owin.RequestMethod", value); }
    }

    /// <summary>
    /// Gets or set the HTTP request scheme from owin.RequestScheme.
    /// </summary>
    /// <returns>The HTTP request scheme from owin.RequestScheme.</returns>
    public virtual string Scheme
    {
        get { return Get<string>("owin.RequestScheme"); }
        set { Set("owin.RequestScheme", value); }
    }

It turns out that OwinContext along with OwinRequest and OwinResponse are just strongly typed wrappers for dictionary that holds all the context data.

Actually, the documentation for OwinContext says pretty much the same:

This wraps OWIN environment dictionary and provides strongly typed accessors.

So don’t pick on the name. It is actually accessing a context data, but you can have multiple instances of wrappers for the same dictionary.

Dependency Injection in Owin

As I mentioned before Owin has it’s own little DI container that is used for internal needs.

Turns out this is not completely true. Owin itself does not have this. However, you can put objects into context dictionary and then retrieve them by the key, it is just a dictionary, it does not have much to it.

The DI functionality I referred to belongs to Asp.Net Identity. Here is an article about intended use. I would not recommend using it for anything else.

When you use app.CreatePerOwinContext<ApplicationDbContext>(ApplicationDbContext.Create), the code registers the delegate (method ApplicationDbContext.Create) in dictionary of middlewares. Once the Owin application is built (calling IAppBuilder.Build()) , this delegate is executed and instance of ApplicationDbContext is stored in OwinContext.Environment dictionary with type name as a key. Later when code is calling OwinContext.Get<ApplicationDbContext>(), this dictionary is looked by typename, casted to correct type and returned:

public virtual T Get<T>(string key)
{
    object value;
    return Environment.TryGetValue(key, out value) ? (T)value : default(T);
}

And if we are applying DI terms here, then your object is registered in per-request scope, as you would expect to be DbContext. If you are using a proper DI container, beware that if you register one object in Owin and the same typed of object in your container, these might be different instances and unexpected bugs/exceptions might happen.

Another question I’ve been asked about Identity.

Part of Startup class for Owin can be this:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator
                .OnValidateIdentity<UserManager, ApplicationUser, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                    getUserIdCallback: (id) => (Int32.Parse(id.GetUserId())))
        },
    });
}

The question was “How does SecurityValidator.OnValidateIdentity invalidate all existing cookies” and “I understand that getUserIdCallback delegate returns an id of a user, but I don’t quite see the usefulness of this parameter” and “why the need for regenerateIdentityCallback parameter“.

regenerateIdentityCallback is a delegate taking UserManager and ApplicationUser objects as parameters and returns a new ClaimsIdentity object. Seems strange to have a separate callback for that because default implementation of UserManager already has CreateIdentityAsync which does work for us. But signature of that method looks like this:

public virtual Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)

See the authentication type as a parameter? without having a global setting for what type of authentication we use, there is no way know what authentication we use. So part of that delegate somehow should be authentication type.

Regarding getUserIdCallback – things are simple here. UserId is stored in cookie as a claim. But it is stored as a string. All claims are stored as strings. If you use default type for the key (String), then no problem here. But if you use Guid or int for primary key type, things get more complex. So this peace of code needs to know how to convert String with id into Guid or int.

To answer very first question “How does SecurityValidator.OnValidateIdentity invalidate all existing cookies“. Well.. it does not really invalidates all the cookies. Cookie contains issued date. On every request SecurityValidator compares if enough time have passed from cookie issue (30 minutes in the sample code above). Then it gets a UserId (via getUserIdCallback delegate) and SecurityStamp values from the cookie. Reaches into the database, finds the user and checks if SecurityStamp have been changed since the cookie have been set.
If security stamp is not changed, fresh cookie is created with new issue date. If stamp have been changed, user is logged out.

And this happens on every request. So it could be that user have logged in Firefox, a minute after security stamp have been updated for that user. User will not be logged out from Firefox for another 29 minutes. And imagine that session in Chrome was started 29 minutes before change of security stamp, so cookie in Chrome will be invalidated in 1 minute.

UserManager registration

If you notice regenerateIdentityCallback is using UserManager and ApplicationUser as part of the callback:

regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager)

How does it get an instance of UserManager? OwinContext is used for that:

var manager = context.OwinContext.GetUserManager<TManager>();

How does OwinContext know about where to get an instance of UserManager? Good question!
You must tell OwinContext how to create UserManager:

app.CreatePerOwinContext(() => new UserManager(new MyDbContext()));

Or if you are using DI in your MVC application:

app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<UserManager>());

Or if you are using standard MVC template from Visual Studio 2013:

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

CreatePerOwinContext function registers a callback in a dictionary. And once this call returns an instance, this instance is saved in a Dictionary<String, object> for later user. Basically OWIN has it’s own little DI-container where it keeps references to objects that should be singletons during the request.

If cookie validation function can’t get an instance of UserManager, it will not be able to compare the security stamp in cookie with security stamp in the database and the CookieValidator won’t be able to invalidate the cookie. So your code should look like this:

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(() => new UserManager(new MyDbContext()));

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator
                .OnValidateIdentity<UserManager, ApplicationUser, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                    getUserIdCallback: (id) => (Int32.Parse(id.GetUserId())))
        },
        // other configurations
    });

    // other stuff
}

I’ve been reached out by one of my readers with a list of questions about AspNet Identity. First I thought the questions will be easy and I’ll wing them, but turned out that every single question in the list is worth of a separate blog post. So I’ll do a mini-series of Q-A posts about Identity framework and related stuff.

First question is about security token in a Cookie and how it is computed: Identity Framework creates a token in the cookie, token containing the same information (User.Id, Security Stamp, etc.); if the same user loggen-in in Chrome and Firefox, why are the cookies different?

I did think about it for a while, I guessed that cookie creation and expiration is encoded in the cookie, along with some sort of signature of the cookie. My guess was not far from the real world.

Fortunately, the code that deals with cookies is in Katana Project and is open-sourced.

Here is the pipeline how cookie is created on user sign-in:

  1. Identity framework creates ClaimsPrincipal object from the record in your database (that is represented by ApplicationUser class)
  2. Identity adds list of default claims like ApplicationUser.Id and SecurityStamp to the claims on the principal.
  3. ClaimsPrincipal is passed to OWIN middleware: CookieAuthenticationHandler
  4. Authentication Handler is doing a lot of checking for different things, like should the cookie be marked as secure or persistent, sets the expiry date and many other things. Result of these checks is AuthenticationTicket which has ClaimsIdentity with list of claims and AuthenticationProperties which is a dictionary with load of data like cookie issue date, expiry date, is cookie persistent, etc.
  5. Auth ticket and claims principal is then passed down to SecureDataFormat class where data is serialised, encrypted and Base64 encoded.

The last step contains a lot of movements, let’s look deeper into it.

Authentication ticket is serialised via TicketSerializer. There ClaimsIdentity is written into memory stream: some properties and list of the claims. Then AuthenticationProperties (with cookie set, expiry dates) is also written to memory stream. Then this memory stream is GZipped and returned for further processing.

Next step in the pipeline is encryption. Encryption is borrowed from .Net class DpapiDataProtector. You can read documentation on MSDN. I’m not sure about the strength of the encryption. The documentation says that purpose parameters are effectively a list of passwords. And nowhere I’ve seen in OWIN where you can set your own encryption password and I can see that the main password is set to “Microsoft.Owin.Security.IDataProtector”. So my guess would be that no secure information should go into cookie, i.e. don’t put your connection strings into user claims!

After the encryption, stream of bytes is Base64-encoded to be transferable over the wire. And finally prepared to be set as a cookie header on HTTP Response.

Overall the process will look like this great drawing:

Cookie_Path

Anyway, the answer to the original question why the cookies are different in different browsers would be as follows: because part of the signature contains cookie creation and expiry dates, these would be different in different browsers. So data encrypted in cookie turns out to be different, the value of the cookie will be different.