一. 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 = ;
options.Password.RequiredUniqueChars = ; // Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();
options.Lockout.MaxFailedAccessAttempts = ;
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(); 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 = ;
options.Password.RequiredUniqueChars = ; // Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();
options.Lockout.MaxFailedAccessAttempts = ;
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

 

asp.net core系列 46 Identity介绍的更多相关文章

  1. asp.net core系列 39 Razor 介绍与详细示例

    原文:asp.net core系列 39 Razor 介绍与详细示例 一. Razor介绍 在使用ASP.NET Core Web开发时, ASP.NET Core MVC 提供了一个新特性Razor ...

  2. asp.net core系列 48 Identity 身份模型自定义

    一.概述 ASP.NET Core Identity提供了一个框架,用于管理和存储在 ASP.NET Core 应用中的用户帐户. Identity添加到项目时单个用户帐户选择作为身份验证机制. 默认 ...

  3. asp.net core系列 52 Identity 其它关注点

    一.登录分析 在使用identity身份验证登录时,在login中调用的方法是: var result = await _signInManager.PasswordSignInAsync(Input ...

  4. asp.net core系列 49 Identity 授权(上)

    一.概述 授权是指用户能够访问资源的权限,如页面数据的查看.编辑.新增.删除.导出.下载等权限.ASP.NET Core 授权提供了多种且灵活的方式,包括:Razor pages授权约定.简单授权.R ...

  5. asp.net core系列 47 Identity 自定义用户数据

    一.概述 接着上篇的WebAppIdentityDemo项目,将自定义用户数据添加到Identity DB,自定义扩展的用户数据类应继承IdentityUser类, 文件名为Areas / Ident ...

  6. asp.net core 系列 19 EFCore介绍

    一.概述 目前最新的EF Core版本是3.0,最稳定的EF Core版本是2.2.EF Core 的计划与 .NET Core以及 ASP.NET Core 版本同步.EF Core 是一个 .NE ...

  7. asp.net core系列 51 Identity 授权(下)

    1.6 基于资源的授权 前面二篇中,熟悉了五种授权方式(对于上篇讲的策略授权,还有IAuthorizationPolicyProvider的自定义授权策略提供程序没有讲,后面再补充).本篇讲的授权方式 ...

  8. asp.net core系列 50 Identity 授权(中)

    1.5 基于策略的授权 在上篇中,已经讲到了授权访问(authorization)的四种方式.其中Razor Pages授权约定和简单授权二种方式更像是身份认证(authentication) ,因为 ...

  9. asp.net core系列 66 Dapper介绍--Micro-ORM

    一.概述 目前对于.net的数据访问ORM工具很多,EF和EF Core是一个重量级的框架.最近在搭建新的项目架构,来学习一下轻量级的数据访问ORM工具Dapper.Dapper支持SQL Serve ...

随机推荐

  1. [ SSH框架 ] Struts2框架学习之一

    一.Struts2框架的概述 Struts2是一种基于MVC模式的轻量级Web框架,它自问世以来,就受到了广大Web开发者的关注,并广泛应用于各种企业系统的开发中.目前掌握 Struts2框架几乎成为 ...

  2. 【已解决】C#中往SQLServer插入数据时遇到BUG

    错误信息如下: “System.Data.SqlClient.SqlException”类型的未经处理的异常在 System.Data.dll 中发生 其他信息: “”附近有语法错误. 文字版代码如下 ...

  3. SQL Server性能优化(8)堆表结构介绍

    一.表结构综述 下图是SQL Server中表的组织形式(其中分区1.分区2是为了便于管理,把表进行分区,放到不同的硬盘数据文件里.默认情况下,表只有一个分区.).表在硬盘上的存放形式,有堆和B树两种 ...

  4. 软件及博客的markdown支持度的评测

    软件 vscode vscode原生支持markdown,但对数学公式的支持不太好,用 $$包含的数学公式不支持换行,而且在数学公式里面不能输入中文 Typora 非常简洁优美的软件,只有预览页,没有 ...

  5. 浮点型 float和double类型的内存结构和精度问题

    首先引用一个例子在java中可能你会遇到这样的问题: 例:0.99999999f==1f //true 0.9999999f==1f //false 这是超出精度造成的,为了知道为什么会造成这样的问题 ...

  6. [ 搭建Redis本地服务器实践系列 ] :序言

    说起来,是在一个气候适宜的下午,虽然临近下班,不过办公室里还是充满了忙碌的身影,不时的还会从办公区传来小伙伴们为了一个需求而激烈争论的声音,自从入了互联网这个行业,说实话,也就很少休息了,当然了也不全 ...

  7. 前端开发中的JS调试技巧

    前言:调试技巧,在任何一项技术研发中都可谓是必不可少的技能.掌握各种调试技巧,必定能在工作中起到事半功倍的效果.譬如,快速定位问题.降低故障概率.帮助分析逻辑错误等等.而在互联网前端开发越来越重要的今 ...

  8. java中使用hashSet的特性,判断数组是否有重复值

    public static boolean cheakRepeat(int[] array){ HashSet<Integer> hashSet = new HashSet<Inte ...

  9. SSM-SpringMVC-02:SpringMVC最简单的小案例

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 咱们这个案例做什么? 就是用处理器代替Servlet处理请求 开发步骤: 1.引入jar包 <!--单 ...

  10. linux 安装 PHP fileinfo 扩展

    将windows解压Linux服务器 1.错误: PHP Fileinfo extension must be installed/enabled to use Intervention Image. ...