asp.net core Identity Framework
2022/2/18 1:12:51
本文主要是介绍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"); } }
这篇关于asp.net core Identity Framework的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#