【问题标题】:Using ASP.NET Core Identity with MongoDB在 MongoDB 中使用 ASP.NET Core 标识
【发布时间】:2022-01-08 21:50:51
【问题描述】:

我目前正在尝试结合 MongoDB 学习 ASP.NET Core 3.1。我已经可以执行简单的 CRUD 操作了。现在我想设置与 MongoDB 相关的 ASP.NET Core Identity。为此,我安装了以下 Nuget 包:

  • AspNetCore.Identity.Mongo(8.1.0 版)
  • AspNetCore.Identity.MongoDbCore(版本 3.1.1)

在 Configure 方法的 IdentityHostingStartup 类中,我现在正在执行以下代码:

builder.ConfigureServices((context, services) => {
            services.AddIdentityMongoDbProvider<ApplicationUser, MongoRole>(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;
            }, options => {
                options.ConnectionString = "mongodb://localhost:27017/MyDB";
                options.UsersCollection = "ApplicationUser";
                options.RolesCollection = "clientRole";
            }).AddDefaultUI();

            // 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;
            });
        });

但我在编译之前收到以下错误:

“MongoIdentityOptions”不包含“Password”的定义,并且找不到接受“MongoIdentityOptions”类型的第一个参数的可访问扩展方法“Password”(您是否缺少 using 指令或程序集引用?)

我从here获得了代码。

我尝试先注释掉对 identityOptions 的所有访问。但是在编译代码之前出现以下错误:

“Application.Areas.Identity.Data.ApplicationUser”不能用作泛型类型或方法“MongoIdentityExtensions.AddIdentityMongoDbProvider(IServiceCollection, Action, Action)”中的类型参数“TUser”。没有从“Application.Areas.Identity.Data.ApplicationUser”到“AspNetCore.Identity.Mongo.Model.MongoUser”的隐式引用转换。

我做错了什么?

【问题讨论】:

标签: c# asp.net mongodb asp.net-core identity


【解决方案1】:

我也遇到了同样的情况,结果是我混淆了README.md 为 AspNetCore.Identity.Mongo 提供的示例。为了创建我的 ApplicationUser,我按照示例使用不同的主键类型,所以它看起来像这样:

public class ApplicationUser : MongoUser<string>
{
    // Additional properties
}

因此在 ConfigureServices 中需要以下内容(注意不同的类型参数):

services.AddIdentityMongoDbProvider<ApplicationUser, ApplicationRole, string>(identity =>
    {
        identity.Password.RequiredLength = 8;
        // other options
    },
    mongo =>
    {
        mongo.ConnectionString = "mongodb://127.0.0.1:27017/identity";
        // other options
    });

事实证明,我不需要使用不同的主键类型。因此,我删除了它,并且能够使用 AddIdentityMongoDbProvider 方法,该方法仅具有 User 和 Role 的类型参数,就像您在示例中所做的那样。删除主键类型参数后,我的 ApplicationUser 看起来像这样:

public class ApplicationUser : MongoUser
{
    // Additional properties
}

【讨论】:

    【解决方案2】:

    我真的不敢相信每个人都在没有启用安全性的情况下使用 MongoDb。 我花了很多时间试图让它与安全的 URL 一起工作,比如

    mongodb://superuser:changeMeToAStrongPassword@localhost:27017/?authSource=admin&authenticationDatabase=admin
    

    因此,对于 MongoDbGenericRepository,有必要将 DB 名称传递给 ctor,对于身份提供者,它应该在第一个 / 之后的字符串中。

    这对我有帮助并且适用于这两种情况,因此我可以为 Identity 重新定义 dbName 并将其与 Repository 一起使用

    mongodb://superuser:changeMeToASstrongPassword@localhost:27017/{0}?authSource=admin&authenticationDatabase=admin

    然后像这样

        services.AddIdentityMongoDbProvider<User, MongoRole<Guid>, Guid>(options =>
                {
                    options.Password.RequireDigit = true;...
                },
                mongo =>
                {
                    mongo.ConnectionString = string.Format(
                        Configuration.GetConnectionString("MongoDb"),
                        "myProject_users");
                })
    

    【讨论】:

      猜你喜欢
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多