5

ASP.NET Core 3.1 Identity is an API to simplify backend and logical code to manage users, passwords, profile data, roles, claims, tokens, email confirmation, and more.

For Visual Studio, it support scaffolding to provide multiple templates page but requires DataContext that relies on Entity Framework, which currently support CosmosDB for Core 3.1, the only NoSQL database.

What are the options available to implement ASP.NET Core Identity and allow scaffolding?

1 Answer 1

8

Use Mongo Identity NuGet packages available on the public as the replacement for default ASP.NET Core Identity. Few packages that's still in maintain are AspNetCore.Identity.Mongo and AspNetCore.Identity.MongoDbCore.

  1. Install the latest package in NuGet (see above).

  2. Right click on your project in "Solution Explorer" panel > Add > New Scaffolded Item...

    Select "Identity" on the left panel, and double click on Identity in the main selection panel

  3. In "Add Identity" windows, select all or the page you would like to use.

    Click on "+" button besides Data context class input, add a new one (name doesn't matter as you could delete it afterwards), and do the same for User class (name it well, such as ApplicationUser, this will be the one you'll be using in later development, changing it would take some time and lots of hassle)

    for User class, you can rename it as Namespace, such as "[Your Project].Areas.Identity.Datas.ApplicationUser", this will be reflected on scaffold code.

3.1. If required, you could add Role class, it would be better to create on the same namespace as User class to categorize your code.

  1. Open file "IdentityHostingStartup.cs" in [Your Project]/Areas/Identity, replace code with the guide from GitHub, additional settings information can be found here
// 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 https://stackoverflow.com/questions/52089864/

// 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;
});
  1. Register Authentication service at Configure() method in Startup.cs folder
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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, I'm trying to do as seggested but I got an error on build which says "'TestIdentityMongo.Areas.Identity.Data.TestIdentityMongoUser' cannot be used as type parameter 'TUser' in the generic type or method 'IdentityDbContext<TUser>'. There is no implicit reference conversion from 'TestIdentityMongo.Areas.Identity.Data.TestIdentityMongoUser' to 'Microsoft.AspNetCore.Identity.IdentityUser'." not sure if I'm doing something bad. Looks like the MongoUser class is now obsolete.
Hello @ste.xin, I am not sure about it, but there's other alternatives you can try, such as github.com/alexandre-spieser/AspNetCore.Identity.MongoDbCore, I will edit this answer to reflect on better approach i've found
Im trying to setup a Blazor Server App with mongoDB and Identity. but when im pasting the code for the "IdentityHostingStartup.cs" file, i always get the error: "iservicecollection does not contain a definition for "addidentitymongodbprovider" what am i doing wrong?

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.