在本章中,无涯教程将安装和配置Identity框架,这仅需要一点工作,如果转到Visual Studio并创建一个新的ASP.NET Core应用程序,然后选择完整的Web应用程序模板,并将身份验证设置为单个用户帐户,则该新项目将包括为您设置的Identity框架的所有内容。
从一个空项目开始,现在,将从头开始创建Identity框架,这是学习完整应用程序模板中所有部分的一种好方法,因为如果您没有仔细研究所有代码,可能会造成混淆。
首先,需要安装依赖项,即 Microsoft.AspNet.Identity 。将通过安装 Microsoft.AspNet.Identity.EntityFramework 继续,然后实现与Entity Framework一起使用的Identity框架。
如果依赖Identity.EntityFramework,则该包将包含Identity包。
如果您构建自己的数据存储,则可以仅使用Identity软件包。
一旦安装了依赖项,就可以创建一个Customer User类,其中包含要存储的有关用户的所有信息。
对于此应用程序,将从Identity框架提供的类中继承,该类将为提供所有必要的知识,如Username属性和存储哈希密码的位置。
还需要修改FirstAppDemoDbContext 类,以从Identity框架的 IdentityDb 类继承。
IdentityDb提供了使用实体框架存储为用户信息所需的一切。设置了User类并设置了 DBContext 之后,将需要使用Startup类的 ConfigureServices 方法将Identity Services配置到应用程序中。
就像需要添加服务来支持MVC框架一样,Identity框架也需要将服务添加到应用程序中才能正常工作。
这些服务包括 UserStore 服务和 SignInManager 。
将把这些服务注入控制器中,以创建用户并在适当的时间发布cookie。
最后,在启动Configure方法期间,将需要添加Identity中间件。
该中间件不仅有助于将cookie转换为用户身份,还可以确保用户不会看到带有401响应的空白页面。
现在让按照下面给出的步骤进行操作。
第1步 - 需要添加对Identity框架的依赖关系,将Microsoft.AspNet.Identity.EntityFramework依赖项添加到project.json文件中,这将包括需要的所有其他必要的身份软件包。
{ "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "EntityFramework.Commands": "7.0.0-rc1-final", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { }, "dnxcore50": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] }
第2步 - 保存此文件, Visual Studio将还原软件包,现在,可以添加User类,通过右键单击Models文件夹并选择Add→Class来添加User类。
将该类称为"User",然后单击"Add"按钮,如上面的屏幕截图所示,在此类中,您可以添加属性以保存要存储的有关用户的任何信息。
第3步 - 从Identity框架提供的类派生User类,Identity.EntityFramework命名空间中的是IdentityUser类。
using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Models { public class User : IdentityUser { } }
第4步 - 现在,转到IdentityUser,将光标放在该符号上,然后按F12键以查看Visual Studio的元数据视图。
#region Assembly Microsoft.AspNet.Identity.EntityFramework, Version=3.0.0.0, namespace Microsoft.AspNet.Identity.EntityFramework { public class IdentityUser : IdentityUser<string> { public IdentityUser(); public IdentityUser(string userName); } }
第5步 - 您可以看到IdentityUser是从字符串的IdentityUser派生的,您可以通过派生IdentityUser并指定通用类型参数来更改主键的类型。
第6步 - 现在将光标放在字符串的IdentityUser上,然后再次按F12进入元数据视图。
现在,您可以在默认情况下查看与用户有关的所有信息。
第7步 - 现在,无涯教程需要确保User包含在DBContext中,因此打开应用程序中具有的 FirstAppDemoDBContext ,而不是直接从内置的Entity Framework基类DBContext派生它,现在需要从IdentityDbContext。
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; namespace FirstAppDemo.Models { public class FirstAppDemoDbContext : IdentityDbContext<User> { public DbSet<Employee> Employees { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB; Initial Catalog=FirstAppDemo;Integrated Security=True; Connect Timeout=30;Encrypt=False;TrustServerCertificate=True; ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); } } }
第8步 - IdentityDbContext类也位于Microsoft.AspNet.Identity.EntityFramework命名空间中,可以指定应存储的用户类型。这样,添加到User类的任何其他字段都将进入数据库。
IdentityDbContext带来了其他DbSet,不仅用于存储用户,而且还包含有关用户角色和用户声明的信息。
User类现在准备就绪,FirstAppDemoDbContext类配置为与Identity框架一起使用。
现在可以进入Configure和ConfigureServices来设置身份框架。
第9步 - 现在从 ConfigureServices 开始,除了MVC服务和实体框架服务之外,还需要添加身份服务,这将添加Identity框架执行工作所依赖的所有服务。
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<FirstAppDemoDbContext> (option => option.UseSqlServer(Configuration["database:connection"])); services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>(); }
AddIdentity方法采用两个通用类型参数-用户实体的类型(User entity)和角色实体(role entity)的类型。
这两个通用类型参数是用户的类型-刚刚创建的User类和要使用的Role类,现在将使用内置的IdentityRole。此类位于EntityFramework命名空间中。
当使用带有身份的实体框架时,还需要调用第二种方法-AddEntityFrameworkStores。
链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_core/asp.net-core-identity-configuration.html
来源:LearnFk无涯教程网
AddEntityFrameworkStores方法将配置诸如UserStore之类的服务,该服务用于创建用户并验证其密码。
第10步 - 下面两行是为应用程序配置服务所需的全部。
services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>();
第11步 - 还需要添加中间件,插入中间件的位置很重要,因为如果在管道中插入中间件的时间太晚,它将永远没有机会处理请求。
而且,如果无涯教程需要在MVC控制器内部进行授权检查,则需要在MVC框架之前插入身份中间件,以确保成功处理Cookie和401错误。
public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); app.UseFileServer(); app.UseIdentity(); app.UseMvc(ConfigureRoute); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); }
第12步 - 插入中间件的位置就是添加身份中间件的位置,以下是Startup.cs文件的完整实现。
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using FirstAppDemo.Services; using Microsoft.AspNet.Routing; using System; using FirstAppDemo.Entities; using Microsoft.Data.Entity; using FirstAppDemo.Models; using Microsoft.AspNet.Identity.EntityFramework; namespace FirstAppDemo { public class Startup { public Startup() { var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json"); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; } //This method gets called by the runtime. //Use this method to add services to the container. //For more information on how to configure your application, //visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<FirstAppDemoDbContext>(option => option.UseSqlServer(Configuration["database:connection"])); services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>(); } //This method gets called by the runtime. //Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); app.UseFileServer(); app.UseIdentity(); app.UseMvc(ConfigureRoute); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } private void ConfigureRoute(IRouteBuilder routeBuilder) { //Home/Index routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"); } //Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
第13步-现在让续构建应用程序,在下一章中,需要添加另一个Entity Framework迁移,以确保无涯教程的SQL Server数据库中具有Identity模式。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Python实战 · 从0到1搭建直播视频平台 -〔Barry〕