asp.net core Identity 用户管理 框架的配置

ASP.NET Core Identity是一个会员身份系统,早期它的名字是Membership,当然那是一段“古老”的历史,现在我们来了解全新的Identity。它允许我们创建、读取、更新和删除账户。支持账号验证、身份验证、授权、恢复密码和SMS双因子身份验证。它还支持微软、Facebook和Google等第三方登录提供商。它提供了一个丰富的API,并且这些API还可以进行大量的扩展。

Identity 支持跨数据库

下面开始 asp.net core 实战配置。所有代码 都是 使用 .net6 如有其他版本 笔者会 标明清楚

1.首先 创建 MyUser.cs 文件

using Microsoft.AspNetCore.Identity;

namespace aspnetcore013
{
    public class MyUser:IdentityUser<long>//long是主键的类型
    {
        //这里是 自定义的自增 字段 会创建到 数据库中 AspNetUsers表中
        public string? WeChat { get; set; }
    }
}

2. 创建 MyRole.cs 文件


using Microsoft.AspNetCore.Identity;

namespace aspnetcore013
{
    public class MyRole:IdentityRole<long>//long是主键的类型
    {

    }
}

3. 创建 MyDBcontext.cs 文件 这里要注意 IdentityDbContext<MyUser,MyRole,long> 设置相关联

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace aspnetcore013
{
    public class MyDBcontext:IdentityDbContext<MyUser,MyRole,long>
    {
        public MyDBcontext(DbContextOptions<MyDBcontext> options)
           : base(options)
        {
        }
    }
}

4. 在 Program.cs 中 如下 配置

builder.Services.AddDbContext<MyDBcontext>(opt =>
{
    opt.UseSqlServer("Data Source=ADMIN\\MSSQLSERVER2012A;Initial Catalog=demo10;User ID=sa;Password=123456");
});
builder.Services.AddDataProtection();
builder.Services.AddIdentityCore<MyUser>(opt =>
{
    //自定义的配置
    opt.Password.RequireDigit = false;
    opt.Password.RequiredLength = 6;
    opt.Password.RequireLowercase = false;
    opt.Password.RequireNonAlphanumeric = false;
    opt.Password.RequireUppercase = false;
    opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
    opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
});
IdentityBuilder identityBuilder = new IdentityBuilder(typeof(MyUser),typeof(MyRole),builder.Services);
identityBuilder.AddEntityFrameworkStores<MyDBcontext>().AddDefaultTokenProviders()
    .AddUserManager<UserManager<MyUser>>().AddRoleManager<RoleManager<MyRole>>();

5.开始 做迁移 Add-migration 和 updade-database

使用的 nuget包 如下

Microsoft.AspNetCore.Identity.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值