Asp.Net Core-Identity 配置

在本章中,我们将安装和配置Identity框架,这只需要一点点工作。 如果您使用Visual Studio并创建一个新的ASP.NET Core应用程序,并选择具有设置为单个用户帐户的完整Web应用程序模板,该新项目将包括为您设置的Identity框架的所有。


我们从一个空的项目开始。 我们现在将从头开始设置Identity框架,这是一个了解完整应用程序模板中所有部分的好方法,因为如果您没有详细了解所有代码的话,它可能会引起混淆。

最开始,我们将需要安装依赖项,即Microsoft.AspNet.Identity。 我们将继续安装Microsoft.AspNet.Identity.EntityFramework,然后实现与Entity Framework一起使用Identity框架。

  • 如果我们对Identity.EntityFramework有依赖性,则这个包已经包含Identity包。

  • 如果您构建自己的数据存储,您可以使用Identity包工作。

  • 我们的依赖安装完成后,我们可以创建一个客户User类,其中包含我们想要存储的关于用户的所有信息。

  • 对于这个应用程序,我们将继承一个由Identity框架提供的类,该类将为我们提供所有的必需品,如Username属性和一个存储散列密码的地方。


  • 我们还需要修改我们的FirstAppDemoDbContext类,以继承Identity框架的IdentityDb类。

  • IdentityDb为我们提供了作为用户信息与实体框架存储所需的一切。 一旦我们设置了User类和DBContext,我们将需要使用Startup类的ConfigureServices方法将Identity服务配置到应用程序中。

  • 就像我们需要添加服务来支持MVC框架一样,Identity框架需要为应用程序添加服务才能工作。

  • 这些服务包括类似UserStore服务和SignInManager的服务。

  • 我们将把这些服务注入到我们的控制器中,以便在适当的时间创建用户和发出cookie。

  • 最后,在启动的配置方法中,我们将需要添加Identity中间件。

  • 这个中间件不仅有助于将cookie转换为用户身份,而且还确保用户没有看到401响应的空页面。

让我们现在按照下面的步骤。

步骤1 - 我们需要继续添加一个Identity框架的依赖。 让我们将Microsoft.AspNet.Identity.EntityFramework依赖项添加到project.json文件中。 这将包括我们需要的所有其他必要的Identity包。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    "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,并单击添加按钮,如上面的屏幕截图。 在此类中,您可以添加属性以保存要存储有关用户的任何信息。

步骤3 - 让我们从Identity框架提供的类派生User类。 它是在Identity.EntityFramework命名空间中的IdentityUser类。

1
2
3
4
5
6
7
8
9
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的元数据视图。

1
2
3
4
5
6
7
#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以转到元数据视图。


默认情况下,您现在可以看到与用户相关的所有信息。 信息包括以下内容 -

  • 我们不会在此应用程序中使用,但可以使用的字段。

  • Identity框架可以跟踪特定用户的失败登录尝试次数,并可以在一段时间内锁定该帐户。

  • 存储PasswordHash的字段,PhoneNumber。 我们将使用的两个重要字段是PasswordHash和UserName。

  • 我们还将隐式地使用用户的主键和ID属性。 如果您需要查询特定用户,也可以使用该属性。

步骤7 - 现在,我们需要确保User包含在我们的DBContext中。 所以,让我们打开我们在应用程序中的FirstAppDemoDBContext,而不是直接从DBContext(它是内置的Entity Framework基类)中导出,现在我们需要从IdentityDbContext派生它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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带来了额外的DbSets,不仅存储用户,还包括用户角色和用户声明的信息。

  • 我们的User类现在就绪了。 我们的FirstAppDemoDbContext类配置为使用Identity框架。

  • 我们现在可以进入Configure和ConfigureServices来设置Identity框架。

步骤9 - 让我们现在从ConfigureServices开始。 除了我们的MVC服务和我们的Entity Framework服务,我们需要添加我们的Identity服务。 这将添加Identity框架依赖的所有服务来完成其工作。

1
2
3
4
5
6
7
8
9
10
11
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类和我们要使用的Role类。 我们现在将使用内置的IdentityRole。 这个类在EntityFramework命名空间中。

  • 当我们使用Entity Framework with Identity时,我们还需要调用第二个方法 - AddEntityFrameworkStores。

  • AddEntityFrameworkStores方法将配置像UserStore这样的服务,用来创建用户和验证他们的密码的服务。

步骤10 - 以下两行是我们需要为应用程序配置服务。

1
2
services.AddIdentity<User, IdentityRole>() 
    .AddEntityFrameworkStores<FirstAppDemoDbContext>();

步骤11 - 我们还需要添加中间件。 我们插入中间件的位置很重要,因为如果我们在管道中插入中间件太晚,它将永远不会有机会处理请求。

如果我们需要在我们的MVC控制器内部进行授权检查,我们需要在MVC框架之前插入Identity中间件,以确保cookie和401错误被成功处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 - 我们插入中间件的位置是我们将添加Identity中间件的位置。 以下是Startup.cs文件的完整实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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, 
       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模式。

版权声明:本站所有教程均为本站原创或翻译,转载请注明出处,请尊重他人劳动果实。请记住本站地址:www.yuanjiaocheng.net (猿教程) 作者:卿文刚
本文标题: Asp.Net Core-Identity 配置 
本文地址:http://www.yuanjiaocheng.net/ASPNET-CORE/core-identity-configuration.html
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值