集成ASP.NETCore Identity
学习分享 丨作者 / 郑 子 铭 丨公众号 / DotNet NB / CloudNative NB
任务24:集成ASP.NETCore Identity
之前在 Index 页面写了一个 strong 标签,需要加个判断再显示,不然为空没有错误的时候也会显示
@if (!ViewContext.ModelState.IsValid)
{
<strong>Error""</strong>
<div asp-validation-summary="All" class="danger"></div>
}因为 asp-validation-summary 是 asp.net view 视图会自动控制,而 strong 不会,所以要显示标题需要添加一个判断,那么这里我们直接移除掉,当有错误信息的时候直接显示即可,这里作为上一节的补充
<div asp-validation-summary="All" class="danger"></div>这一节主要把 Identity 加入进来
一开始我们把 startup 中的 Identity 注释掉了,只需要开启即可
添加包 IdentityServer4,IdentityServer4.AspNetIdentity,添加之后就可以把 AddTestUsers 移除掉,它就不会再用测试里面的 user,
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<ApplicationUser, ApplicationUserRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryClients(Config.GetClients())
.AddInMemoryApiResources(Config.GetApiResource())
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddAspNetIdentity<ApplicationUser>();
//services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
// .AddCookie(options => {
// options.LoginPath = "/Account/Login";
// });
//services.Configure<IdentityOptions>(options =>
//{
// options.Password.RequireLowercase = true;
// options.Password.RequireNonAlphanumeric = true;
// options.Password.RequireUppercase = true;
// options.Password.RequiredLength = 12;
//});
services.AddScoped<ConsentService>();
services.AddMvc();
}接下来要到 AccountController 中切换回原先的登录逻辑
AccountController
接下来改造 AccountController 的 Register 方法,首先把 RegisterViewModel 的 UserName 改回为 Email
RegisterViewModel
AccountController
接着改造 AccountController 的 Login 方法,首先把 LoginViewModel 的 UserName 也改回为 Email,并加上一个 RememberMe 字段
LoginViewModel
调用 UserManager 的查找和登录的逻辑
AccountController
还原 Logout 方法
Logout
检查一下 view,将 Login.cshtml 里面的 UserName 修改为 Email,model 改为 LoginViewModel
Login.cshtml
恢复 Program 中 EF 的初始化
Program
启动程序之后会根据 appsettings.json 中的配置创建数据库
appsettings.json
编译启动程序,可以看到用户表有一条数据

这条数据来自 ApplicationDbContextSeed
浏览器访问
使用邮箱登录

退出登录之后启动客户端,浏览器访问 5001 之后会跳转到 5000
输入邮箱和密码之后会来到 consent 页面

点击同意之后跳转到 MvcClient

点击 About 看到用户名是 Administrator,就是数据库里面的用户

这就是我们把程序里面的 TestUserStore 替换为 Identity
end
Last updated