Course contentsShow
← C#
Lesson 1190 of 1,90811. Identity, Security, and ClaimsFree lesson

Customizing Identity Stores

Swap the default Entity Framework Core stores for custom implementations like Redis or NoSQL databases.

In this lesson, you will learn how to decouple ASP.NET Core Identity from its default Entity Framework Core implementation to store user data in alternative databases like Redis or NoSQL providers.

The Identity Store Architecture

By default, ASP.NET Core Identity uses UserStore and RoleStore, which rely on EF Core to map your ApplicationUser class to a relational database. However, if your application requires extreme read performance or a non-relational document structure, you can swap these out.

The architecture is built on the Provider Pattern. The Identity framework exposes interfaces such as IUserStore<TUser>, IUserPasswordStore<TUser>, and IQueryableUserStore<TUser>. By implementing these interfaces, you define exactly how the system fetches, saves, and deletes users without relying on a DbContext.

Swapping the Implementation

To move away from EF Core, you create a class that implements the required Identity interfaces. For example, if you were implementing a Redis store, your IUserStore would handle the serialization logic:

public class RedisUserStore : IUserStore<ApplicationUser>
{
    public async Task<IdentityResult> CreateAsync(ApplicationUser user, CancellationToken ct)
    {
        // Serialize user object to JSON and save to Redis cache
        await _redis.StringSetAsync(user.Id, JsonSerializer.Serialize(user));
        return IdentityResult.Success;
    }
    
    // Implement remaining methods like FindByIdAsync, UpdateAsync, etc.
}

Once your custom store is ready, you register it in your Program.cs file using the Identity builder. This tells the dependency injection container to ignore the default EF stores and inject your custom logic instead:

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddUserStore<RedisUserStore>()
    .AddRoleStore<RedisRoleStore>();

Why do this?

While EF Core is excellent for general relational needs, custom stores provide granular control. You might use this to integrate with a legacy LDAP system, a high-speed NoSQL cluster for real-time authentication, or a proprietary microservice that manages identity externally. The framework is designed to be storage-agnostic, meaning your controllers and authentication logic remain identical regardless of whether your user data lives in SQL Server or a memory cache.

Key Takeaway: By implementing the IUserStore and IRoleStore interfaces, you can replace the default Entity Framework Core storage with any database provider, allowing your application to scale or integrate with external identity systems.