你还在为不会使用.NET Core做登录注册角色分配而烦恼吗?现在,这篇文章即将告诉你如何使用.NET Core的组件进行简单的登录注册和角色分配的功能,文章将会教你实现以下功能:
1、.NET Core自带的Identity组件的安装与使用;
2、实现注册功能;
3、实现登录功能;
4、实现退出与修改密码功能;
5、角色分配与授权;
6、数据库的简单CRUD
1、使用Identity组件
使用vs2022的.NET 6进行演示。我们需要以下nuget包:
第一个包就是我们需要的Identity相关组件,安装完成后,需要进行如下步骤:
创建Domain层用于存放聚合根和Dto,文件位置如下:
创建用户基本信息,由于是演示,我们不需要组件。
public class ApplicationUser:IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string? ProfilePicture { get; set; }
}
创建聚合根。
public class DatabaseContext:IdentityDbContext<ApplicationUser>
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
}
在program里进行依赖注入。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<DatabaseContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("conn")));
//安全组件添加
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddDefaultTokenProviders();
//添加cookie
builder.Services.ConfigureApplicationCookie(options => options.LoginPath = "/UserAuthentication/Login");
var app = builder.Build();
配置连接字符串。
"ConnectionStrings": {
"conn": "Data Source=to.db"
}
重定义路由。
app.MapControllerRoute(
name: "default",
pattern: "{controller=UserAuthentication}/{action=Login}/{id?}");
添加授权鉴权。
app.UseAuthentication();
app.UseAuthorization();
使用如下指令进行迁移:
add-migration init
update-database
现在,你已经连接了sqlite数据库,当然,连接其他的数据库也可以。
2、实现注册的功能
现在,我们需要把Repository完善,然后依赖注入。首先需要的是实现注册登录退出相关的功能,我们使用Identity和DTO层来完成数据平面化。
关于注册的DTO层建立代码如下。
public class Register_Dto
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Username { get; set; }
[Required]
[RegularExpression("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*[#$^+=!*()@%&]).{6,}$", ErrorMessage = "最小长度为6,必须包含1个大写、1个小写、1个特殊字符和1个数字")]
public string Password { get; set; }
[Required]
[Compare("Password")]
public string PasswordConfirm { get; set; }
public string? Role { get; set; }
}
在AuthRepository的注册实现方法如下:
public async Task<Status> RegisterAsync(Register_Dto model)
{
var status = new Status();
var userExists = await userManager.FindByNameAsync(model.Username);
if (userExists != null)
{
status.StatusCode = 0;
status.StatusMessage = "用户已存在";
return status;
}
ApplicationUser user = new ApplicationUser()
{
Email = model.Email,
SecurityStamp = Guid.NewGuid().ToString(),
UserName = model.Username,
FirstName = model.FirstName,
LastName = model.LastName,
EmailConfirmed = true,
PhoneNumberConfirmed = true,
};
var result = await userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
status.StatusCode = 0;
status.StatusMessage = "注册失败";
return status;
}
if (!await roleManager.RoleExistsAsync(model.Role))
await roleManager.CreateAsync(new IdentityRole(model.Role));
if (await roleManager.RoleExistsAsync(model.Role))
{
await userManager.AddToRoleAsync(user, model.Role);
}
status.StatusCode = 1;
status.StatusMessage = "注册成功";
return status;
}
在控制器的注册方法如下:
public IActionResult Registration()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Registration(Register_Dto model)
{
if (!ModelState.IsValid)
return View(model);
model.Role = "User";
var result = await repository.RegisterAsync(model);
TempData["msg"]=result.StatusMessage;
return RedirectToAction(nameof(Registration));
}
前端界面大致如下:
@model LoginRegistrationtrainingMVC.Models.Dto.Register_Dto
@{
Layout = null;
}
@Html.ValidationSummary()
<div class="container">
<div class="row">
<div class="col-md-6 center-block">
<h3>Registration</h3>
<form asp-action="Registration" method="post">
<div class="form-group">
<label>F</label>
<input type="text" class="form-control" asp-for="FirstName"/>
<span class="text-danger" asp-validation-for="FirstName"></span>
</d