惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
T
Tailwind CSS Blog
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
H
Help Net Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Last Week in AI
Last Week in AI
A
About on SuperTechFans
L
LangChain Blog
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
G
Google Developers Blog
The Cloudflare Blog
云风的 BLOG
云风的 BLOG
D
Docker
博客园 - 聂微东
博客园 - 司徒正美
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
U
Unit 42

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
MongoDB-backed ASP.NET Core Identity, without the EF Core...
Michael Jordan · 2026-06-25 · via DEV Community

Michael Jordan

If you're already running MongoDB and you reach for ASP.NET Core Identity, the
official story points you at Entity Framework Core. That's a fine answer if you
have a relational database. If you don't, you end up bolting a second data
access stack onto an app that has exactly one store. You don't need it.

AspNetCoreIdentity.MongoDriver is a store provider that talks to Mongo through
the official MongoDB.Driver directly — no EF Core, no SQL, no second
persistence model. It implements the Identity store interfaces, ships a
UserStore and RoleStore, and wires up UserManager/RoleManager the way
you already expect.

The 15-line version

Register the provider in Program.cs:

builder.Services.AddIdentityMongoDbProvider<MongoUser<Guid>, MongoRole<Guid>, Guid>(identity =>
{
    identity.User.RequireUniqueEmail = true;
}, mongo =>
{
    mongo.ConnectionString = builder.Configuration.GetConnectionString("MongoDb")!;
});

A connection string like mongodb://localhost:27017/Identity creates an
Identity database and stores the collections there. That's the whole setup.
Now inject the managers wherever you need them:

public class AccountController(UserManager<MongoUser<Guid>> userManager) : Controller
{
    // ...
}

They're registered as scoped services — let the container manage their
lifetime. Don't call BuildServiceProvider() yourself, and don't cache the
managers in long-lived objects.

Your key type is yours

The MongoUser and MongoRole classes are generic, so the primary key isn't
forced to be a Guid. Want string keys? Use MongoUser<string>. If you use
string keys and don't assign an Id on create, the store generates an
ObjectId-style string for you.

If you do go with Guid, register the serializer once before the code above so
Mongo stores them in the standard representation:

BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

Migrations that survive a rolling deploy

Here's the part that usually bites people who hand-roll a Mongo store. On the
first store operation — not during service registration — the library:

  • applies any pending schema migrations, guarded by a distributed lock so that if several app instances boot at once, the migrations apply exactly once; and
  • creates its indexes: a unique index on NormalizedUserName, an index on NormalizedEmail, a compound index on Logins.LoginProvider / Logins.ProviderKey, and a unique index on the role NormalizedName.

That distributed lock matters the moment you run more than one instance. Two
pods starting simultaneously won't race each other into a half-applied schema.

Because the NormalizedUserName index enforces real uniqueness, index creation
will fail if your existing data already contains duplicate user names — clean
those up before you upgrade. If you'd rather own these concerns yourself, set
mongo.DisableIndexCreation = true and/or mongo.DisableAutoMigrations = true.
And if you want the work done at startup instead of on first request, resolve
MongoIdentityInitializer and await EnsureInitializedAsync().

It won't silently clobber concurrent writes

Updates and deletes use optimistic concurrency through Identity's
ConcurrencyStamp. If the document changed since you loaded your copy, the
operation returns a ConcurrencyFailure instead of overwriting the other
write. Reload, reapply, retry — the normal Identity dance.

One honest limitation

options.Stores.ProtectPersonalData is not supported. The store doesn't
encrypt personal data at rest, and rather than letting you flip that switch and
quietly store unprotected data anyway, enabling it throws at runtime. If you
need encryption-at-rest for PII, handle it at a different layer.

Try it

dotnet add package AspNetCoreIdentity.MongoDriver

If you're on Mongo and Identity, this is the short path. Issues and PRs welcome.