如何使用 MongoDB 实现 ASP.NET Core 3.1 Identity?

wui*_*ang 4 c# mongodb asp.net-identity asp.net-core-3.1

ASP.NET Core 3.1 Identity是一个 API,用于简化后端和逻辑代码来管理用户、密码、配置文件数据、角色、声明、令牌、电子邮件确认等。

对于 Visual Studio,它支持脚手架提供多个模板页面,但需要DataContext依赖于Entity Framework,目前实体框架支持 CosmosDB for Core 3.1,这是唯一的 NoSQL 数据库。

有哪些选项可用于实现 ASP.NET Core Identity 并允许搭建脚手架?

wui*_*ang 7

使用公开提供的 Mongo Identity NuGet 包作为默认 ASP.NET Core Identity 的替代品。仍在维护的软件包很少有AspNetCore.Identity.MongoAspNetCore.Identity.MongoDbCore

  1. 在 NuGet 中安装最新的包(见上文)。

  2. 在“解决方案资源管理器”面板中右键单击您的项目 > 添加 > 新支架项目...

    在左侧面板中选择“Identity”,然后双击主选择面板中的“Identity”

  3. 在“添加身份”窗口中,选择您要使用的全部或页面。

    单击数据上下文类输入旁边的“+”按钮,添加一个新的(名称并不重要,因为您可以稍后删除它),并对用户类执行相同的操作(命名好,例如ApplicationUser,这将是您将在以后的开发中使用它,更改它需要一些时间和很多麻烦)

    对于 User 类,您可以将其重命名为 Namespace,例如“[Your Project].Areas.Identity.Datas.ApplicationUser”,这将反映在脚手架代码上。

3.1. 如果需要,您可以添加 Role 类,最好在与 User 类相同的命名空间上创建以对代码进行分类。

  1. 在 [您的项目]/Areas/Identity 中打开文件“IdentityHostingStartup.cs”,将代码替换为 GitHub 中的指南,其他设置信息可以在此处找到
// Add Identity for AspNetCore.Identity.Mongo, ApplicationRole is optional
services.AddIdentityMongoDbProvider<ApplicationUser, ApplicationRole>(identityOptions =>
{
    // Password settings.
    identityOptions.Password.RequiredLength = 6;
    identityOptions.Password.RequireLowercase = true;
    identityOptions.Password.RequireUppercase = true;
    identityOptions.Password.RequireNonAlphanumeric = false;
    identityOptions.Password.RequireDigit = true;

    // Lockout settings.
    identityOptions.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    identityOptions.Lockout.MaxFailedAccessAttempts = 5;
    identityOptions.Lockout.AllowedForNewUsers = true;

    // User settings.
    identityOptions.User.AllowedUserNameCharacters =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    identityOptions.User.RequireUniqueEmail = true;
}, mongoIdentityOptions => {
    mongoIdentityOptions.ConnectionString = "mongodb://localhost:27017/MyDB";
    // mongoIdentityOptions.UsersCollection = "Custom User Collection Name, Default User";
    // mongoIdentityOptions.RolesCollection = "Custom Role Collection Name, Default Role";
}).AddDefaultUI(); //.AddDefaultUI() to temporary remove error when no EmailSender provided, see /sf/ask/3646290511/

// This is required to ensure server can identify user after login
services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});
Run Code Online (Sandbox Code Playgroud)
  1. 在文件夹Configure()中的方法中注册身份验证服务Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // code here...
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    // add app.UseAuthentication(); to register authentication service, without it, user could technically login but has no logged in session created.
    app.UseAuthentication();
    app.UseAuthorization();
    // more code
}
Run Code Online (Sandbox Code Playgroud)