.net core identity(一)简单运用

1.net core identity涉及到很多知识,很多概念包括Claims,Principal等等概念需要我们一步步学习才能掌握其原理,有两篇博客是比较好的介绍该框架的,

https://segmentfault.com/a/1190000014966349

http://www.cnblogs.com/savorboard/p/aspnetcore-identity.html

2.我在这里先不涉及到上面2篇博客提到的较为高深的内容,而是按照Adam Freeman的.net core mvc中相关代码来做一个小例子

3.首先我们需要明确一个概念是AspNetCore.Identity这一框架是为我们身份认证和权限管理统一做出的抽象,使我们可以通过实现相关接口或方法来完成身份认证的模块,

而不用自己去实现相关繁复的功能.那么下面就进入正题

4.Microsoft.AspNetCore.Identity 命名空间下IdentityUser 为我们定义了用户身份的基类,这里展示一部分属性

 1 public class IdentityUser<TKey> where TKey : IEquatable<TKey>{
 2 
 3     public IdentityUser();
 4     
 5     public IdentityUser(string userName);
 6 
 7     public virtual DateTimeOffset? LockoutEnd { get; set; }
 8 
 9     public virtual int AccessFailedCount { get; set; }
10 
11     public virtual string UserName { get; set; }
12 
13     public virtual string Email { get; set; }
14 
15 }

5.我们可以通过实现IdentityUser来使用

1     public class AppUser: IdentityUser
2     {
3          //加入其它属性
4     }

6.实现IdentityDbContext配置上下文能用到ef的相关功能

1  public class AppIdentityDbContext: IdentityDbContext<AppUser>
2     {
3 
4         //public DbSet<AppUser> appuser
5         public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options)
6                         : base(options) { }
7     }

7.Startup启动类配置,

AddIdentity方法指定用户和用户的角色类,我们用我们定义的AppUser 和系统定义的IdentityRole
AddEntityFrameworkStores 用于配置应用Ef哪个上下文来对用户信息做存储
AddDefaultTokenProviders用于配置令牌的实现,是cookie还是jwt等等,这一块不熟,
最后利用app.UseAuthentication()将identity加入管道中.

下面的一下配置用来配置用户名,邮箱,密码的一些规则,可以不写

 1  services.AddDbContext<AppIdentityDbContext>(options =>
 2                                     options.UseSqlServer(Configuration["Data:SportStoreIdentity:ConnectionString"]));
 3 
 4
 5   services.AddIdentity<AppUser, IdentityRole>(option=> {
 6                 //邮箱必须唯一
 7                 option.User.RequireUniqueEmail = true;
 8                 //用户名只许小写字母拼写
 9                 option.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz";
10                 option.Password.RequiredLength = 6;
11                 option.Password.RequireNonAlphanumeric = false;
12                 option.Password.RequireLowercase = false;
13                 option.Password.RequireUppercase = false;
14                 option.Password.RequireDigit = false;
15 
16             })
17               .AddEntityFrameworkStores<AppIdentityDbContext>()
18                     .AddDefaultTokenProviders();

        public void Configure(IApplicationBuilder app) {
                    app.UseStatusCodePages();
                    app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}

 8.createModel 和Controller,可以看出UserManager是对用户信息做出管理的一个类,你们可以进入看看有什么方法,最后调用就不用我说了吧

1 public class CreateModel {
2 [Required]
3 public string Name { get; set; }
4 [Required]
5 public string Email { get; set; }
6 [Required]
7 public string Password { get; set; }
8 }
 1 public class AdminController : Controller
 2     {
 3 
 4        private UserManager<AppUser> userManager;
 5        public AdminController(UserManager<AppUser> usrMgr
 6         {
 7             userManager = usrMgr;
 8         }  
 9       

          public IActionResult Index(){
                     return View(userManager.Users);
          }

10       public ViewResult Create() => View();      
11 
12       [HttpPost]
13         public async Task<IActionResult> Create(CreateModel model)
14         {
15             if (ModelState.IsValid)
16             {
17                 AppUser user = new AppUser
18                 {
19                     UserName = model.Name,
20                     Email = model.Email
21                 };
22 
23                 IdentityResult result
24                 = await userManager.CreateAsync(user, model.Password);
25                 if (result.Succeeded)
26                 {
27                     return RedirectToAction("Index");
28                 }
29                 else
30                 {
31                     foreach (IdentityError error in result.Errors)
32                     {
33                         ModelState.AddModelError("", error.Description);
34                     }
35                 }
36             }
37             return View(model);
38         }
39 
40 }

9.果然是技术不够,写这么点就有点力不从心,真是羡慕那些长篇大论的大神,这就是我的理解,肯定有欠缺的地方,望大家指正

猜你喜欢

转载自www.cnblogs.com/Spinoza/p/10026328.html
今日推荐