• asp.net core 使用Identity Framework实现账户管理


    用到的package

        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.2" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlserver" Version="6.0.2" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.tools" Version="6.0.2">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
    

    定义User/Role实体类

        public class MyUser : IdentityUser<long>
        {
            public string? WechatAccount { get; set; }
        }
    
        public class MyRole : IdentityRole<long>
        {
        }
    
        public class MyDbContext : IdentityDbContext<MyUser, MyRole, long>
        {
            public MyDbContext(DbContextOptions<MyDbContext> options)
                : base(options)
            {
    
            }
        }
    

    注入identity framework

    builder.Services.AddDbContext<MyDbContext>(opt =>
    {
        opt.UseSqlServer("Server=.;Database=demo06;Trusted_Connection=True;MultipleActiveResultSets=True");
    });
    builder.Services.AddDataProtection();
    builder.Services.AddIdentityCore<MyUser>(options =>
    {
        options.Password.RequireDigit = false;
        options.Password.RequireLowercase = false;
        options.Password.RequireUppercase = false;
        options.Password.RequiredLength = 4;
        options.Password.RequireNonAlphanumeric = false;
        options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
        options.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
    });
    
    IdentityBuilder idBuilder = new IdentityBuilder(typeof(MyUser), typeof(MyRole), builder.Services);
    idBuilder.AddEntityFrameworkStores<MyDbContext>()
        .AddDefaultTokenProviders().AddRoleManager<RoleManager<MyRole>>()
        .AddUserManager<UserManager<MyUser>>();
    

    在Controller中使用usermanager/rolemanager实现帐户的操作

        [ApiController]
        [Route("[controller]")]
        public class IdentityController : ControllerBase
        {
            private UserManager<MyUser> UserManager { get; init; }
            private RoleManager<MyRole> RoleManager { get; init; }
    
            public IdentityController(UserManager<MyUser> userManager, RoleManager<MyRole> roleManager)
            {
                UserManager = userManager;
                RoleManager = roleManager;
            }
    
            [HttpPost("AddRole")]
            public async Task<ActionResult<string>> AddRole(string roleName)
            {
                if (await RoleManager.RoleExistsAsync(roleName))
                    return BadRequest("role already existed");
    
                MyRole role = new MyRole() { Name = roleName };
                IdentityResult result = await RoleManager.CreateAsync(role);
    
                if (!result.Succeeded)
                    return BadRequest("create role failed");
    
                return Ok("ok");
            }
    
            [HttpPost("AddUser")]
            public async Task<ActionResult<string>> AddUser(string roleName, string userName, string password)
            {
                MyUser user = await UserManager.FindByNameAsync(userName);
    
                if (user == null)
                {
                    user = new MyUser()
                    {
                        UserName = userName,
                        Email = $"{userName}@ccc.com",
                        EmailConfirmed = true
                    };
                    IdentityResult result = await UserManager.CreateAsync(user, password);
                    if (!result.Succeeded)
                        return BadRequest("create role failed");
                }
    
                MyRole role = await RoleManager.FindByNameAsync(roleName);
                if (role == null)
                    return BadRequest("role could not be found.");
    
                if (!await UserManager.IsInRoleAsync(user, roleName))
                {
                    IdentityResult result = await UserManager.AddToRoleAsync(user, roleName);
    
                    if (!result.Succeeded)
                        return BadRequest("add user to role failed");
                }
    
                return Ok("ok");
            }
    
            [HttpPost("Login")]
            public async Task<ActionResult<string>> Login(string username, string password)
            {
                MyUser user = await UserManager.FindByNameAsync(username);
    
                if (user == null)
                    return NotFound("username or password is wrong");
    
                if (await UserManager.IsLockedOutAsync(user))
                    return BadRequest("user locked out");
    
                if (await UserManager.CheckPasswordAsync(user, password))
                {
                    await UserManager.ResetAccessFailedCountAsync(user);
                    return Ok("Success");
                }
    
                await UserManager.AccessFailedAsync(user);
                return NotFound("username or password is wrong");
            }
    
            [HttpPost("ForgetPassword")]
            public async Task<ActionResult<string>> ForgetPassword(string username)
            {
                MyUser user = await UserManager.FindByNameAsync(username);
    
                if (user == null)
                    return NotFound("username not found");
    
                string token = await UserManager.GeneratePasswordResetTokenAsync(user);
                return Ok(token);
            }
    
            [HttpPost("ResetPassword")]
            public async Task<ActionResult<string>> ResetPassword(string token, string username, string password)
            {
                MyUser user = await UserManager.FindByNameAsync(username);
    
                if (user == null)
                    return NotFound("username not found");
    
                IdentityResult result = await UserManager.ResetPasswordAsync(user, token, password);
                if (!result.Succeeded)
                    return BadRequest("failed to reset password");
    
                await UserManager.ResetAccessFailedCountAsync(user);
                return Ok("ok");
            }
        }
    
  • 相关阅读:
    OilPaint(转载/实验)
    UE4 3D artist
    render pipeline about (翻译)
    Python 相对导入 碎碎念
    USF, USH Grammar
    JZ19 顺时针打印矩阵
    JZ49 把字符串转换成整数
    JZ45 扑克牌顺子
    JZ53 表示数值的字符串
    JZ48 不用加减乘除做加法
  • 原文地址:https://www.cnblogs.com/mryux/p/15906477.html
Copyright © 2020-2023  润新知