Best practices for integrating ASP.NET Identity -

2019-02-02 17:58发布

问题:

I'm using ASP.NET Identity with a new website and there don't seem to be many (any?) examples of how to do this in a decoupled manner. I do not want my domain model's DomainUser class to have to inherit from Microsoft.AspNet.Identity.EntityFramework.User, so I've created a class that looks like this:

public class IdentityUser : User
{
    public virtual DomainUser DomainUser { get; private set; }
}

I've moved the DbSets required by ASP.NET Identity into the same derived DbContext class as my domain models as illustrated in this answer. I've linked the IdentityUser unidirectionally to the DomainUser via Fluent API like so:

modelBuilder.Entity<IdentityUser>().HasRequired(iu => iu.DomainUser).WithRequiredPrincipal();

This allows me to mostly separate the concerns of authorization and authentication from the behaviors defined in the DomainUser class. This is better than combining them into one class, but it still feels ugly. I still have references to the required ASP.NET Identity assemblies in my Domain project. I could create yet another project that held only my IdentityUser class and a reference to my Domain assembly to allow for the navigation property, but that starts to feel convoluted.

I feel like there should be a better, cleaner, more modular way to link Identity up to the domain without it resulting in tight coupling.

Has anyone come up with a better way of handling this? I'm hoping to garner the attention of those involved in the ASP.NET Identity project (Hao Kung et al) to provide direction here.

回答1:

There is a discussion on decoupling ASP.NET Identity here. And you can find examples on how it as implemented in the open source project SimpleSecurity.



回答2:

The fact is that if you're going to inherit from IdentityUser, ASP.NET Identity related assemblies are coming along for the ride. You can't separate Identity from ASP.NET. The original examples in the question don't buy you much- in most cases you're probably better off just inheriting from IdentityUser if you're going to be using IdentityUser in your Domain project.

If your domain project truly needs to be free of ASP.NET related assemblies then you can leave the Identity related classes in your web project and create a separate User model in your Domain project an link the two programmatically, as suggested here.