65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET Core Identity:使用 ASP.NET Core MVC 实现用户注册、登录和注销功能

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.48/5 (10投票s)

2017年11月25日

CPOL

2分钟阅读

viewsIcon

78750

使用 ASP.NET Core MVC 和 Identity 进行身份验证

引言

这是关于 ASP.NET Core Identity 的系列文章的第二篇。

在上一篇文章中,我们设置了一个带有 Identity 数据库的项目。 在本文中,我们将使用该项目来实现使用 ASP.NET Core MVC 的用户身份验证功能。

本文的完整代码可在该 repo 的 Demo 2 文件夹中找到 https://github.com/ra1han/aspnet-core-identity

准备服务和中间件

我们必须将 MVC 添加到 ConfigureServices 方法中,以便在应用程序中使用它。

我们已经知道,Startup 类中的 Configure 方法用于配置应用程序的中间件。 当前,它具有以下代码,直接写入“Hello World”响应。 我们将删除它并添加 MVC,它将处理请求。

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!");
});

这两个方法的最终代码如下所示

public void ConfigureServices(IServiceCollection services)
{
	services.AddDbContext<applicationdbcontext>(options =>
					options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

	services.AddIdentity<applicationuser, identityrole="">()
														.AddEntityFrameworkStores<applicationdbcontext>()
														.AddDefaultTokenProviders();
	services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

	app.UseAuthentication();

	app.UseMvc(routes =>
	{
		routes.MapRoute(
			name: "default",
			template: "{controller=Home}/{action=Index}/{id?}");
	});
}

准备 ViewModel

在此,我们将创建两个 viewmodel,用于在 RegistrationLogin 页面中使用。

  • LoginViewModel
  • RegisterViewModel

准备控制器

我们将创建两个控制器

  • AccountController
  • HomeController

HomeController 的样子如下

[Authorize]
public class HomeController : Controller
{
	public IActionResult Index()
	{
		return View();
	}
}

这里重要的是我们正在使用控制器的 [Authorize] 属性。 这意味着如果用户未经过身份验证,则他无法访问此端点。

Account 控制器的样子如下(为了简洁,我仅显示 public 方法签名)

[Authorize]
public class AccountController : Controller
{
	public AccountController(UserManager<applicationuser> userManager, 
                             SignInManager<applicationuser> signInManager)
	{
		_userManager = userManager;
		_signInManager = signInManager;
	}

	[HttpGet]
	[AllowAnonymous]
	public async Task<iactionresult> Login(string returnUrl = null)
	{
	}

	[HttpPost]
	[AllowAnonymous]
	[ValidateAntiForgeryToken]
	public async Task<iactionresult> Login(LoginViewModel model, string returnUrl = null)
	{
	}

	[HttpPost]
	[ValidateAntiForgeryToken]
	public async Task<iactionresult> Logout()
	{
	}

	[HttpGet]
	[AllowAnonymous]
	public IActionResult Register(string returnUrl = null)
	{
	}

	[HttpPost]
	[AllowAnonymous]
	[ValidateAntiForgeryToken]
	public async Task<iactionresult> Register(RegisterViewModel model, string returnUrl = null)
	{
	}
}

我们可以看到,与 RegistrationLogin 相关的所有方法都具有 [AllowAnonymous] 属性,以便只有登录用户才能访问它们。

对于注册和身份验证,我们正在使用 UserManagerSignInManager。 它们都是 ASP.NET Core Identity 的一部分,并通过依赖注入提供。

准备视图

视图是在 Views 文件夹中创建的。 我没有过多地解释它们,因为它们是相当标准的 MVC 视图。

使用应用程序

如果运行应用程序,它将进入登录页面,因为没有用户登录。

如果进入注册页面,它将如下所示

注册并登录后,页面将如下所示

这是基于 Cookie 的身份验证,在下一篇文章中,我们将了解如何在 ASP.NET Core Identity 中实现基于 Token 的身份验证。

© . All rights reserved.