1.安装所需要的nuget包
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.24" /><PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.24" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.24" /><PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.24">
2.注入sqlserver数据库服务完成identity数据库的迁移
"ConnectionStrings": {"defaultsql": "server=.;uid=sa;pwd=peng@123;database=ide"}
builder.Services.AddDbContext<IdentityDbContext>(p =>{p.UseSqlServer(builder.Configuration.GetConnectionString("defaultsql"), b => b.MigrationsAssembly("Log4NetTest"));});
3.在程序包管理控制台执行下面依次命令,完成用户权限管理表的迁移
add-migration init
update-datebase
执行完后,数据库就多了下面的表
4.创建一个用户账号的类用于登录和注册
public class account{public string usename { get; set; }public string password { get; set; }}
5.注入identity服务
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
6.注册
private SignInManager<IdentityUser> _signInManager;private UserManager<IdentityUser> _userManager;public WeatherForecastController( SignInManager<IdentityUser> signInManager){_signInManager = signInManager;_userManager = userManager;}/// <summary>/// 注册/// </summary>/// <param name="usename"></param>/// <param name="pwd"></param>[HttpPost]public async Task<string> Register(string usename, string pwd){IdentityUser user = new IdentityUser(){UserName = usename};var result = await _userManager.CreateAsync(user, pwd);if (result.Succeeded){return "添加成功";}return "失败";}
执行swagger查询数据库,添加了一条数据(表示注入成功)
6.登录
/// <summary>////// 登录/// </summary>/// <param name="usename"></param>/// <param name="pwd"></param>[HttpPost]public async Task<string> Login(string usename, string pwd){var user = await _userManager.FindByNameAsync(usename);if (user != null){var re = await _signInManager.PasswordSignInAsync(user, pwd, false, false);if (re.Succeeded){return "登录成功";}return "登录失败";}return "登录失败";}
使用刚才注册的账号,在swagger中调用Login方法,返回登录成功。
补充:代码中使用了微软默认的策略,比如密码的长度限制和复杂度,尝试密码失败次数等。可以根据自己的需求进行更改
builder.Services.Configure<IdentityOptions>(options =>{// 配置密码要求options.Password.RequireDigit = true;//数字options.Password.RequireLowercase = true;//小写字母options.Password.RequireUppercase = true;//大写字母options.Password.RequireNonAlphanumeric = true;//特殊字符options.Password.RequiredLength = 8;//密码长度// 配置用户锁定选项options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);//锁定时间options.Lockout.MaxFailedAccessAttempts = 5;//失败次数options.Lockout.AllowedForNewUsers = true;// 配置用户登录选项options.SignIn.RequireConfirmedEmail = false;options.SignIn.RequireConfirmedPhoneNumber = false;});
7.新增角色
private RoleManager<IdentityRole> _roleManager;public WeatherForecastController(RoleManager<IdentityRole> roleManager){_roleManager = roleManager;}/// <summary>/// 添加角色/// </summary>[HttpPost]public async Task<string> AddRole(string RoleName){var rolename = await _roleManager.RoleExistsAsync(RoleName);if (rolename){return "角色已经存在了";}IdentityRole role = new IdentityRole(){Name = RoleName,};var result = await _roleManager.CreateAsync(role);if (result.Succeeded){return "添加成功";}else{return "添加失败";}}
8.获取所有角色
/// <summary>/// 获取所有角色/// </summary>/// <returns></returns>[HttpGet]public List<IdentityRole> GetRoleList(){return _roleManager.Roles.ToList();}
9.给用户分配角色
/// <summary>/// 给用户分配角色/// </summary>[HttpPost]public async Task<string> UserToRole(string userName, string roleName){var user = await _userManager.FindByNameAsync(userName);if (user != null){var IsExist = await _userManager.IsInRoleAsync(user, roleName);if (!IsExist){var result = await _userManager.AddToRoleAsync(user, roleName);if (result.Succeeded){return "分配成功";}else{return "分配失败";}}}return "用户不存在";}
10.给角色授权(在program中添加策略)(使用策略)
builder.Services.AddAuthorization(options =>{options.AddPolicy("RequireAdminRole", policy =>policy.RequireRole("Admin"));});app.UseAuthentication();app.UseAuthorization();//只有登录用户并且管理员才能访问[HttpGet][Authorize(Policy = "RequireAdminRole")]public string Print(){return "只有管理员才能访问";}
11.给角色授权(使用claim)
builder.Services.AddAuthorization(options =>{options.AddPolicy("UserManager", policy =>{policy.RequireClaim("用户管理", new string[] { "添加用户", "删除用户", "编辑用户" });});});app.UseAuthentication();app.UseAuthorization();
//给用户添加claim声明
IdentityUser user = new IdentityUser(){UserName = usename};if (result.Succeeded){await _userManager.AddClaimAsync(user, new Claim("用户管理", "添加用户"));return "添加成功";}return "失败";
//只有登录用户并且用户claim包含了用户管理才能访问接口[HttpGet][Authorize(Policy = "UserManager")]public string Print(){return "只有管理员才能访问";}