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");
        }
    }
上一篇:for await of用法


下一篇:前端两个方法按顺序执行