1

I'm currently trying to learn ASP.NET Core 3.1 in combination with MongoDB. I can already perform simple CRUD operations. Now I want to set up ASP.NET Core Identity in connection with MongoDB. For this I have installed the following Nuget packages:

  • AspNetCore.Identity.Mongo (version 8.1.0)
  • AspNetCore.Identity.MongoDbCore (version 3.1.1)

In the IdentityHostingStartup class in the Configure method, I am now executing the following code:

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

But I get the following error before compiling:

'MongoIdentityOptions' does not contain a definition for 'Password' and no accessible extension method 'Password' accepting a first argument of type 'MongoIdentityOptions' could be found (are you missing a using directive or an assembly reference?)

I got the code from here.

I tried to comment out all accesses to identityOptions first. But then I get the following error before compiling the code:

'Application.Areas.Identity.Data.ApplicationUser' cannot be used as type parameter 'TUser' in the generic type or method 'MongoIdentityExtensions.AddIdentityMongoDbProvider<TUser, TRole>(IServiceCollection, Action, Action)'. There is no implicit reference conversion from 'Application.Areas.Identity.Data.ApplicationUser' to 'AspNetCore.Identity.Mongo.Model.MongoUser'.

What am I doing wrong?

1

2 Answers 2

1

I experienced the same and it turned out to be that I had mixed up the examples provided by the README.md for AspNetCore.Identity.Mongo. To create my ApplicationUser I had followed the example to use a different primary key type and so it looked like this:

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

and therefore would have needed the following in ConfigureServices (note the different type parameters):

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

As it turned out, I did not need to use a different primary key type. So I removed it and was able to use the AddIdentityMongoDbProvider method with only type parameters for User and Role as you did in your example. After removing the primary key type parameter, my ApplicationUser looked like this:

public class ApplicationUser : MongoUser
{
    // Additional properties
}
Sign up to request clarification or add additional context in comments.

Comments

0

I really can't believe everyone is using MongoDb without security enabled. I spend a lot of time trying to get it working with secured URL like

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

So for MongoDbGenericRepository it' necessary to pass DB name to ctor and for Identity provider it should be in a string right after first /.

This helped me and works for both cases, so I can redefine dbName for Identity and use it with Repository

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

and then like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.