How to create a custom identity store with ASP .NET core

The basic setup for ASP.NET core is to use the EntityFramework to store identities. However, sometimes we want to do it with a DB that is not listed in entity framework supported storages or to have a full control of how it is being stored.

Our first step is to create at least a custom ApplicationUser, ApplicationRole and an ApplicationUserRole:


public class ApplicationUser: IdentityUser<string>
{
    public ApplicationUser()
    {
    	Id = Guid.NewGuid().ToString("N");
    }
}

public class ApplicationRole: IdentityRole<string>
{
    public ApplicationRole()
    {
    	Id = Guid.NewGuid().ToString("N");
    }
}

public class ApplicationUserRole : IdentityUserRole<string>
{
    public string Id { get; set; } = Guid.NewGuid().ToString("N");
    public string? UserName { get; set; }
    public string? RoleName { get; set; }
}

Now we need to create a store and implement identity interfaces


public class CustomUserStore:
        IUserStore<ApplicationUser>,
        IUserPasswordStore<ApplicationUser>,
        IRoleStore<ApplicationRole>,
        IUserRoleStore<ApplicationUser>
{
    public CustomUserStore() 
    {
    }
    
    /* IMPLEMENTATION */
}

Now we shoud inject this store instead of the default implementation


 services.AddIdentity<ApplicationUser, ApplicationRole>((options) =>
 {
 	options.SignIn.RequireConfirmedAccount = false;
 })
 .AddDefaultTokenProviders();

services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
services.AddTransient<IRoleStore<ApplicationRole>, CustomUserStore>();
services.AddTransient<IUserPasswordStore<ApplicationUser>, CustomUserStore>();
services.AddTransient<IUserRoleStore<ApplicationUser>, CustomUserStore>();

Post a Comment

Previous Post Next Post