一. Identity 介绍
ASP.NET Core Identity 是一个会员系统, 可为 ASP.NET Core 应用程序添加登录功能. 可以使用 SQL Server 数据库配置身份以存储用户名, 密码和配置文件数据. 或者, 可以使用另一个持久性存储, 例如, Azure 表存储. 下面学习如何使用 Identity 注册, 登录以及基架标识.
1.1 Identity 搭建演示
下面使用 vs 2017 来演示:
1. 选择 "文件"> "新建"> "项目".
2. 选择 "ASP.NET Core web 应用程序". 将项目命名 WebAppIdentityDemo 具有项目下载相同的命名空间. 单击 "确定".
3. 选择 ASP.NET Core Web MVC 应用程序, 然后选择更改身份验证.
4. 选择单个用户帐户然后单击确定.
生成的项目包含了 Identity 会员系统, 目录结构如下所示, 生成后的目录结构有疑惑, 怎么没看见 Identity 会员系统相关的 model, Controller,cshtml 等文件, 继续往下了解.
(1) 修改连接字符串
找到 appsettings.JSON 文件, 修改 ConnectionStrings 的数据库连接字符串, 默认是连接本机 sql server 数据库, 我改成了连接远程数据库.
- "ConnectionStrings": {
- "DefaultConnection": "Data Source = 172.168.16.75;Initial Catalog =IdentityDB; User ID = hsr;Password =js*2015;"
- },
(2) 基于生成的迁移代码, 同步到数据库
PM> Update-Database
(3) 配置 Identity 服务
- public void ConfigureServices(IServiceCollection services)
- {
- services.Configure<CookiePolicyOptions>(options =>
- {
- // This lambda determines whether user consent for non-essential cookies is needed for a given request.
- options.CheckConsentNeeded = context => true;
- options.MinimumSameSitePolicy = SameSiteMode.None;
- });
- services.AddDbContext<ApplicationDbContext>(options =>
- options.UseSqlServer(
- Configuration.GetConnectionString("DefaultConnection")));
- services.AddDefaultIdentity<IdentityUser>()
- .AddDefaultUI(UIFramework.Bootstrap4)
- .AddEntityFrameworkStores<ApplicationDbContext>();
- services.Configure<IdentityOptions>(options =>
- {
- // Password settings.
- options.Password.RequireDigit = true;
- options.Password.RequireLowercase = true;
- options.Password.RequireNonAlphanumeric = true;
- options.Password.RequireUppercase = true;
- options.Password.RequiredLength = 6;
- options.Password.RequiredUniqueChars = 1;
- // Lockout settings.
- options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
- options.Lockout.MaxFailedAccessAttempts = 5;
- options.Lockout.AllowedForNewUsers = true;
- // User settings.
- options.User.AllowedUserNameCharacters =
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
- options.User.RequireUniqueEmail = false;
- });
- 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;
- });
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
- }
(4) 确认调用 UseAuthentication 中间件
- public void Configure(IApplicationBuilder App, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- App.UseDeveloperExceptionPage();
- App.UseDatabaseErrorPage();
- }
- else
- {
- App.UseExceptionHandler("/Error");
- App.UseHsts();
- }
- App.UseHttpsRedirection();
- App.UseStaticFiles();
- App.UseCookiePolicy();
- App.UseAuthentication();
- App.UseMvc();
- }
(5) 启动程序, 首页提供了注册, 登录的链接
注册成功后 / Identity/Account/Register, 在数据库中 AspNetUsers 表会新增一条数据 (密码: Asp.netCore123). 注册成功后, 说明数据库连接没有问题, 会跳到登录页 Identity/Account/Login
虽然没有看到 Identity 会员系统相关文件, 其实已经内置由 Razor 类库提供. Identity Razor 类库使用该 Identity Areas 公开端点. 例如:
- /Identity/Account/Login
- /Identity/Account/Logout
- /Identity/Account/Manage
二. 基架标识 (Scaffold Identity )
ASP.NET Core 2.1 及更高版本提供了 ASP.NET Core Identity 作为 Razor 类库. 包含 Identity 的应用程序可以应用基架, 来有选择地添加包含在 Identity Razor 类库 (RCL) 的源代码. 建议生成源代码, 以便修改代码和更改行为 (根据开发需求扩展 Identity). 例如, 可以指示基架生成在注册过程中使用的代码. 生成的代码优先于标识 RCL 中的相同代码. 若要获取的用户界面的完全控制, 并且使用默认 RCL, 等下参考 2.2.
2.1 使用 Scaffold Identity 授权到 MVC 项目
1. 从解决方案资源管理器, 右键单击该项目 > 添加 > 新基架项.
2. 从左窗格添加基架对话框中, 选择标识 > 添加.
3. 在中 ADD 标识添加对话框中, 选择所需的选项.
下面使用现有的数据上下文, 选择所有文件, 以便后面重写, 如下所示.
生成需要重写的文件后, 如下所示 (可以比对上图 1.1 的 Areas 目录), 注意生成的是 razor page 文件, 不是 MVC 视图控制器. 之前上面的疑惑解除了.
2.2 创建完整的 Identity UI 源
上面 2.1 中运行 Scaffold Identity, 保持了对 Identity UI 的完全控制. 以下突出显示的代码显示默认 Identity UI 替换 Identity 在 ASP.NET Core 2.1 Web 应用的更改. 需要执行此操作以具有完全控制权限的 Identity UI.
- public void ConfigureServices(IServiceCollection services)
- {
- services.Configure<CookiePolicyOptions>(options =>
- {
- // This lambda determines whether user consent for non-essential cookies is needed for a given request.
- options.CheckConsentNeeded = context => true;
- options.MinimumSameSitePolicy = SameSiteMode.None;
- });
- services.AddDbContext<ApplicationDbContext>(options =>
- options.UseSqlServer(
- Configuration.GetConnectionString("DefaultConnection")));
- services.AddIdentity<IdentityUser, IdentityRole>()
- //services.AddDefaultIdentity<IdentityUser>()
- .AddDefaultUI(UIFramework.Bootstrap4)
- .AddEntityFrameworkStores<ApplicationDbContext>();
- services.Configure<IdentityOptions>(options =>
- {
- // Password settings.
- options.Password.RequireDigit = true;
- options.Password.RequireLowercase = true;
- options.Password.RequireNonAlphanumeric = true;
- options.Password.RequireUppercase = true;
- options.Password.RequiredLength = 6;
- options.Password.RequiredUniqueChars = 1;
- // Lockout settings.
- options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
- options.Lockout.MaxFailedAccessAttempts = 5;
- options.Lockout.AllowedForNewUsers = true;
- // User settings.
- options.User.AllowedUserNameCharacters =
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
- options.User.RequireUniqueEmail = false;
- });
- //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;
- //});
- services.ConfigureApplicationCookie(options =>
- {
- // Cookie settings
- options.Cookie.HttpOnly = true;
- options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
- options.LoginPath = $"/Identity/Account/Login";
- options.LogoutPath = $"/Identity/Account/Logout";
- options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
- });
- // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
- .AddRazorPagesOptions(options =>
- {
- options.AllowAreas = true;
- options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
- options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
- });
- }
选择修改 Login.cshtml 文件, 在里面随变加点标记 xxxx, 运行显示成功, 以后就可以自定义样式布局和扩展权限功能.
参考文献
ASP.NET Core 上的 Identity 简介
ASP.NET Core 项目中的 scaffold-identity
来源: https://www.cnblogs.com/MrHSR/p/10572462.html