如何使用 MongoDB 实现 ASP.NET Core 3.1 Identity? [英] How to implement ASP.NET Core 3.1 Identity with MongoDB?

查看:177
本文介绍了如何使用 MongoDB 实现 ASP.NET Core 3.1 Identity?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

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

推荐答案

使用公开可用的 Mongo Identity NuGet 包作为默认 ASP.NET Core Identity 的替代品.少数仍在维护中的软件包是 AspNetCore.Identity.MongoAspNetCore.Identity.MongoDbCore.

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. 在 NuGet 中安装最新的包(见上文).

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

在解决方案资源管理器"中右键单击您的项目;面板 >添加 >新的脚手架项目...

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

选择身份";在左侧面板上,然后双击主选择面板中的 Identity

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

在添加身份"中windows,选择所有或您要使用的页面.

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

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

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)

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

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.如果需要,您可以添加 Role 类,最好在与 User 类相同的命名空间上创建以对您的代码进行分类.

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. 打开文件IdentityHostingStartup.cs"在 [Your Project]/Areas/Identity 中,将代码替换为来自 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 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. Startup.cs文件夹中的Configure()方法注册认证服务
  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
}

这篇关于如何使用 MongoDB 实现 ASP.NET Core 3.1 Identity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆