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.

Recently I have found an excellent question on Stackoverflow. The OP asks why does claim added to Idenetity after calling AuthenticationManager.SignIn still persist to the cookie.

The sample code was like this:

ClaimsIdentity identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie );

var claim1 = new Claim(ClaimTypes.Country, "Arctica");
identity.AddClaim(claim1);

AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, identity );

var claim2 = new Claim(ClaimTypes.Country, "Antartica");
identity.AddClaim(claim2);

Yeah, why does claim2 is available after cookie is already set.

After much digging I have discovered that AspNet Identity framework does not set the cookie. OWIN does. And OWIN is part of Katana Project which has open source code. Having the source code available is always nice – you can find out yourself why things work or don’t work the way you expect.

In this case I have spent a few minutes navigating Katana project and how AuthenticationManager works. Turned out that SingIn method does not set a cookie. It saves Identity objects into memory until time comes to set response cookies. And then claims are converted to a cookie and everything magically works -)

This sparked another question. At the moment Identity is does not have open source, but what is the role of OWIN in Identity and how Claims work here?

Turns out that Identity framework deals only with user persistence, password hashing, validating if the password is correct, sending out email tokens for password reset, etc. But Identity does not actually authenticate users or create cookies. Cookies are handled by OWIN.

Take a look on this code for signing in:

public async Task SignInAsync(Microsoft.Owin.Security.IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent)
{
    authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

    ClaimsIdentity identity = await UserManager.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);

    authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

Identity only creates ClaimsIdentity which you can study on ReferenceSource site. And ClaimsIdentity is part of .Net framework, not some nuget-package from the interwebz. Then this claimsIdentity is passed to OWIN AuthenticationManager where a callback is set to assign cookies on when time comes to write headers on the response.

So far, so good, we have 3 parts here: Identity framework creating a ClaimsIdentity, OWIN creating a cookie from this ClaimsIdentity. And .Net framework which holds the class for ClaimsIdentity.

When in your classes you access ClaimsPrincipal.Current, you only use .Net framework, no other libraries are used. And this is very handy!

Default Claims

Identity framework does a nice thing for you. By default it adds a number of claims to a principal when user is logged in. Here is the list:

  • User.Id is added as claim type “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier” or by ClaimTypes.NameIdentifier
  • Username is added as claim type “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name” or by ClaimTypes.Name
  • “ASP.NET Identity” is saved as claim type “http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider“. This is useful if you are using OpenId to do the authentication. Not much use if you are using only users stored in our database. See this page for more details.
  • Guid containing User’s Security Stamp is persisted in claim with type “AspNet.Identity.SecurityStamp“. Security Stamp is basically a snapshot of user state. If password/method of authentication, email, etc. is changed, Security Stamp is changed. This allows to “logout everywhere” on credentials change. Read more about what is security stamp in Hao Kung’s answer.
  • The most useful claims added by default are role. All roles assigned to the user are saved as ClaimTypes.Role or by “http://schemas.microsoft.com/ws/2008/06/identity/claims/role“. So next time you need to check current user’s roles, check the claims. This does not hit the database and is very quick. And in fact, if you call .IsInRole("RoleName") on ClaimsPrincipal, the framework goes into claims and checks if Role claims with this value is assigned.

You can find the list of framework claim types on .Net Reference site. However, this list is not complete. You can make up your own claim types as you are pleased – this is just a string.

If you want to add your own claim types, I recommend to use your own notation for the claim types. Something like “MyAppplication:GroupId” and keep all the claim types in one class as constants:

public class MyApplicationClaimTypes
{
    public string const GroupId = "MyAppplication:GroupId";
    public string const PersonId = "MyAppplication:PersonId";
    // other claim types
} 

This way you can always find where the claims are used and will not clash with the framework claim types. Unless the claim you use matches framework claim types exactly, like ClaimTypes.Email.

Adding default claims

I always add user’s email to the list of claims. I do that on user sign-in, same way the first code snippet adds claim1 and claim2:

public async Task SignInAsync(IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent)
{
    authenticationManager.SignOut(
        DefaultAuthenticationTypes.ExternalCookie,
        DefaultAuthenticationTypes.ApplicationCookie);

    var identity = await this.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);

    // using default claim type from the framework
    identity.AddClaim(new Claim(ClaimTypes.Email, applicationUser.Email));

    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

You can add your default claims to all users here as well. But there is IClaimsIdentityFactory class that is assigned in UserManager. There is only one method there:

public interface IClaimsIdentityFactory<TUser, TKey> where TUser : class, IUser<TKey> where TKey : IEquatable<TKey>
{
    /// <summary>
    /// Create a ClaimsIdentity from an user using a UserManager
    /// </summary>
    Task<ClaimsIdentity> CreateAsync(UserManager<TUser, TKey> manager, TUser user, string authenticationType);
}

Default AspNet Identity implementation creates ClaimsIdentity, adds the default claims described above, adds claims stored in the database for the user: IdentityUserClaims. You can override this implementation and slip-in your own logic/claims:

public class MyClaimsIdentityFactory : ClaimsIdentityFactory<ApplicationUser, string>
{
    public override async Task<ClaimsIdentity> CreateAsync(UserManager<ApplicationUser, string> userManager, ApplicationUser user, string authenticationType)
    {
        var claimsIdentity = await base.CreateAsync(userManager, user, authenticationType);

        claimsIdentity.AddClaim(new Claim("MyApplication:GroupId", "42"));

        return claimsIdentity;
    }
}

and assign it in UserManager:

public UserManager(MyDbContext dbContext)
    : base(new UserStore<ApplicationUser>(dbContext))
{
    // other configurations

    // Alternatively you can have DI container to provide this class for better application flexebility
    this.ClaimsIdentityFactory = new MyClaimsIdentityFactory();
}

When I’d like to find out about technologies used on the site, I look on HTTP header, then on cookies. Usually combination of these can give me a pretty detailed information about underlying technology used. Cookie names are very bad for that – search for any cookie name and you’ll get a lot of information about the technology.

To hide yourself, you can rename cookies from standard to something random. In Asp.Net Identity you can do that via CookieName property on CookieAuthenticationOptions class in configuration:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(0),
            regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
    },
    CookieName = "jumpingjacks",
});

See the jumpingjacks string? that will be the cookie name when users login. You can find the full project source code in my Github repository

There are plenty of articles about how to deploy a solution to Azure Web-Sites. I’ll just leave this here for myself:

msbuild .\SolutionName.sln /p:DeployOnBuild=true /p:PublishProfile=ProfileName /p:Password=passwordForAzurePublishing /p:AllowUntrustedCertificate=true

This builds solution according to previously configured Publish Profile.

  • Good thing that all the configurations parameters are stored within Profile, where you can tell the thing to pre-compile the views and publish to folder where you need it.

  • Bad thing – you can’t specify where deploy to, as that is specified in the Publishing Profile. But you can configure different profiles to publish to testing and to production.

  • Another very bad thing – you can’t provide it with a pre-built web-deploy package, this builds the solution again every time you execute it. And this breaks the rule of Continuous Integration and Deployment: “Build once, deploy everywhere”. Suppose you have a Build Server with process that looks like this: Build => Run Unit Tests => Run Integration Tests => Deploy to Testing => Deploy to Production. And if for deployment you use the line I quoted above, you will be compiling your sources 3 times: first time to run tests, then every time to deploy. In some sense this is OK, because you are building from the same sources, but this is a waste of time. If I build my application with pre-compiled views, this can take a while. One of the applications I work on has 800 views and compilation of all these views takes about 7 minutes. If I compile them once, and re-use that, I don’t need to wait another 7 minutes for deployment to production. Well, OK, OK! Msbuild has got some clever stuff in it and probably will not re-compile all the views if nothing have changed and second time it’ll take less time to do compilation, but that still bothers me. Hopefully new Asp vNext will do something to make my life easier in this sense.

Last week I was updating one of applications I work on to ASP.NET Identity. For a specific reasons I could not deploy to Azure for a while. But I did run all the tests locally and everything worked just fine.

When I mostly finished with Identity conversion, I finally managed to deploy the application to Azure Web-Sites. And it worked fine.. until I tried registering a user.

At that point I had an exception exploding in my face:

System.Security.Cryptography.CryptographicException: The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating.

A bit of digging online did not give me any results. Everything single solution in google was talking about Windows Identity Foundation, but I was not using it. I only have ASP.NET Identity.

After a bit of digging turned out that my application could not generate a token for email confirmation. And that was handled like this:

public class UserManager : UserManager<ApplicationUser>
{
    public UserManager() : base(new UserStore<ApplicationUser>(new MyDbContext()))
    {
        // this does not work on azure!!!
        var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ASP.NET IDENTITY");
        this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"))
        {
            TokenLifespan = TimeSpan.FromHours(24),
        };
    }
}

I have found this snippet somewhere online, but mostly had no idea what it does – cargo culting. My bad! And this very piece was causing issues when run on Azure Web-Sites.

After a lot of messing about with different available options, I came to conclusion there is a good way to do DI injection in UserManager and not take dependency on IdentityFactoryOptions<ApplicationUserManager> in constructor. For that you’ll need to save the reference to IDataProtector as a static where it is available – Startup.Auth.cs:

public partial class Startup
{
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();
        // other stuff.
    }
}

Then you can reach this reference within UserManager

public class UserManager : UserManager<ApplicationUser>
{
    public UserManager() : base(new UserStore<ApplicationUser>(new MyDbContext()))
    {
        var dataProtectionProvider = Startup.DataProtectionProvider;
        this.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));

        // do other configuration
    }
}

I have tried this and it works locally, hosted in IIS and IIS Express. Also just deployed this to Azure and it works in Azure as well, giving nice long user tokens.


After some discussion in the comments, I’ve been shown a better way. Thanks for that, by the way!
The better way is to implement your own IDataProtector, shown in this SO answer

You’ll need to have <machineKey> in your web.config. Usually it looks like this:

<system.web>
    <machineKey validationKey="2EEA416CE..............99E0C" decryptionKey="87..............41A592" validation="SHA1" />
</system.web>

Google for it if you don’t know what it is, there are sites that can generate one for you.

And you’ll need to use MachineKey class in a wrapper:

using System.Web.Security;
using Microsoft.Owin.Security.DataProtection;

public class MachineKeyDataProtector : IDataProtector
{
    private readonly string[] purposes;

    public MachineKeyDataProtector(params string[] purposes)
    {
        this.purposes = purposes;
    }

    public byte[] Protect(byte[] userData)
    {
        return MachineKey.Protect(userData, purposes);
    }

    public byte[] Unprotect(byte[] protectedData)
    {
        return MachineKey.Unprotect(protectedData, purposes);
    }
}

And then in your UserManager specify as following:

public class UserManager : UserManager<ApplicationUser>
{
    public UserManager() : base(new UserStore<ApplicationUser>(new MyDbContext()))
    {
        var machineKeyDataProtector = new MachineKeyDataProtector("ResetPasswordPurpose");
        this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, Guid>(machineKeyDataProtector)
        {
            TokenLifespan = TimeSpan.FromHours(24),
        };
    }
}

I’ve just tried it and works just fine in Azure Web-Site. With a long and scary confirmation code.