Sunday, 2 March 2014

Configuring ASP.NET Identity

[Note: It looks like email is now a first class entity in the database tables as of version of the EF Identity provider]
Recently I’ve been tinkering around with ASP.NET Identity and, like many, have stumbled around in the dark due to lack of documentation – or lack of me being able to find the documentation. Rather than add to the problem I’ll add to the solution, by adding some much-needed documentation as I go.
I have a new project that I want to add ASP.NET Identity to, and after having let the default code whirr around for a while I need to extend it a little. What I want to do is as follows…
  • Add some extra columns to the ‘user’ table
  • Allow email addresses as usernames
I’m sure I may find more things I need to do as I go, but this will do for the moment. I like clear separation of concerns, so am splitting out the data context and associated classes into another assembly for now – that way I can get to grips with it better and also swap it out for something else if necessary. The shell of the solution contains the following classes…
    public abstract class ApplicationUser : IdentityUser
        public string Email { get; set; }

That’s my extended “user” class for now, I’ve added an email property as I need to record that in the database. In my scenario I have two types of user in the system – parents and children. A parent has a username and an email (which may both be the email address), whereas a child may not have an email address.
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        public ApplicationDbContext() : base("DefaultConnection")

This DbContext class derives from the provided IdentityDbContext<TUser> class (that resides in the Microsoft.AspNet.Identity.EntityFramework assembly). You’ll notice that the constructor passes the database connection string “DefaultConnection” to the base class – this is the name used by ASP.NET Identity so I thought I’d use it too. Now to create a user and test what I’ve done so far. I created a simple Console app, created a database in SQL Express, and then fired up the following code…
    using (var ctx = new ApplicationDbContext())
        var store = new UserStore<ApplicationUser>(ctx);
        var manager = new UserManager<ApplicationUser>(store);

        // Now create a user...
        ApplicationUser user = new ApplicationUser
            UserName = "Test",
            Email = ""

        var result = manager.Create(user, "password");

The UserManager class is provided by Microsoft.AspNet.Identity, and is a corollary to the Membership class of old – with a few new bits added for good measure, most notably a load of Task<> methods so you can do all of this stuff asynchronously.

The UserStore class provides an EF based implementation of the IUserStore<TUser> interface. So, if you want to store your users somewhere else, just cruft up an IUserStore<> derived class and you’re away - it’s a very small interface…
    public interface IUserStore<TUser> : IDisposable where TUser : Microsoft.AspNet.Identity.IUser
        Task CreateAsync(TUser user);
        Task DeleteAsync(TUser user);
        Task<TUser> FindByIdAsync(string userId);
        Task<TUser> FindByNameAsync(string userName);
        Task UpdateAsync(TUser user);

Not much to override there should you wish to store and retrieve users from somewhere other than the standard store. However, the user store will probably need to do a lot more than just the above, so there are a bunch of additional interfaces that a user store should consider implementing. These are as follows…

All of these derive from IUserStore<TUser> and the EF provided UserStore class implements the lot. Then there’s a bunch of properties on UserManager that check if the specified user store implements these interfaces and acts accordingly. As an example, you might not want a ‘security stamp’ on your user record – you could create your own class and implement just the bits you need.

Now, UserManager has a bunch of other properties you can set which alter how it does it’s job too. And there’s a bit of strangeness to UserManager which caught me out for a while. I’ve been programming in .NET since 2000 so I’m not a stranger to the odd exception – but when I tried this code I didn’t get any…
    ApplicationUser user = new ApplicationUser
        UserName = "",
        Email = ""

    var result = manager.Create(user, "password");

OK, so that’s created a user – right? Not in my database it hasn’t. This caught me out for a while – there was no user in the database, but also no exception, so what’s up?

Well, after some head scratching I decided to look at the result from this call and saw this…
    "User name is invalid, can only contain letters or digits."

Aha, so that’s my problem. But no exception – hmmm, this library is going to take some getting used to. I cannot remember the last time I explicitly went looking for a “success” code before. What is returned is an IdentityResult instance which includes a Succeeded property and also a bunch of errors in a string collection. Feels like I’m back in the good old days of COM, I’m sure there’s a reason for this design – but that reason was in a meeting probably 3 years ago and hasn’t dribbled down to us. I don’t have an issue with returning multiple errors, that’s fine, but I prefer the way that the Task<> classes do their errors by returning an AggregateException at the end, rather than needing me to plumb the depths of a return code. Oh well.

Permitting emails as usernames

OK, so now to the reason you’re probably here – how do I permit a username to hold an email?

The UserManager class has a UserValidator property which implements IIdentityValidator<TUser>, and the default one doesn’t permit any non-alpha characters in a username. So, you can replace the default, or just alter a property on it as follows…
    var manager = new UserManager<ApplicationUser>(store);
    var val = manager.UserValidator as UserValidator<ApplicationUser>;

    if (null != val)
        val.AllowOnlyAlphanumericUserNames = false;

That’s it – you can now insert usernames that are email addresses. And you could optionally replace the validator with one of your own as you might want to use a regular expression to validate a username, or ensure that the username is not the same as the password and so on. One other thing that the validator does is ensure that no user exists in the database with the same username, which of course your derived class would need to do too.

Adding extra columns to the AspNetUsers table

Due to the magic that is EF 4 (and now 6), by creating my ApplicationUser class above and then adding the Email property (and running against a new database), EF will create the database structure for me so I get a new table with an Email column. Sweet.

By default you get a schema that contains tables prefixed with AspNet, such as AspNetUsers, AspNetRoles and so on. If you want to alter these you can override OnModelCreating in your DbContext class to do something like the following…
    protected override void OnModelCreating(DbModelBuilder modelBuilder)

        modelBuilder.Entity<IdentityUser>().ToTable("Users", "auth");

As an example, the above will store users in a table called Users within the auth schema. Note – if you go down this route I would suggest you don’t call the base class OnModelCreating, and instead copy the code from the base class and alter as necessary (as there’s a few intricacies in there that could bite you).

Wrap Up

With all that in place, I can now store additional information against a user, and I can also use an email address as the username.

No comments: