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;
});