简体   繁体   中英

How to implement ASP.NET Core 3.1 Identity with MongoDB?

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM