Introduction to Identity

66 of 93 people found this helpful

By Pranav Rastogi, Rick Anderson, Tom Dykstra, Jon Galloway and Erik Reitan

ASP.NET Core Identity is a membership system which allows you to add login functionality to your application. Users can create an account and login with a user name and password or they can use an external login providers such as Facebook, Google, Microsoft Account, Twitter and more.

ASP.NET Core身份识别是一个成员身份管理系统,允许向应用中添加登陆功能。用户可创建一个账户并进行登陆,登陆时可使用用户名、密码,或者使用FaceBook, Google, Microsoft Account, Twitter或者其他的外部登陆信息。

You can configure ASP.NET Core Identity to use a SQL Server database to store user names, passwords, and profile data. Alternatively, you can use your own persistent store to store data in another persistent storage, such as Azure Table Storage.

你可以通过配置ASP.NET Core的身份识别,使用SQL Server数据库存储用户名字、密码和配置文件数据。另外,你可使用其他已有的存储空间存储数据,例如Azure Table Storage。

Overview of Identity 身份识别概述

In this topic, you’ll learn how to use ASP.NET Core Identity to add functionality to register, log in, and log out a user. You can follow along step by step or just read the details. For more detailed instructions about creating apps using ASP.NET Core Identity, see the Next Steps section at the end of this article.

本文中,你将学习如何使用ASP.NET Core身份识别技术增加注册、登陆和注销功能。你可以一步一步地跟着学习,也可以仅仅阅读一些细节。更多细节请参看列在本文最后的章节提示。

  1. Create an ASP.NET Core Web Application project in Visual Studio with Individual User Accounts.

1. 使用Indivdual User Accounts创建应用。

In Visual Studio, select File -> New -> Project. Then, select the ASP.NET Web Application from the New Project dialog box. Continue by selecting an ASP.NET Core Web Application with Individual User Accounts as the authentication method.

在Visual Studio中, 选择 File -> New -> Project。然后, 从New Project对话框中选择 ASP.NET Web Application。接着选择 ASP.NET Core Web Application, 并选择 Individual User Accounts 身份认证功能。

The created project contains the Microsoft.AspNetCore.Identity.EntityFrameworkCore package, which will persist the identity data and schema to SQL Server using Entity

创建的项目包含了Microsoft.AspNetCore.Identity.EntityFramewordCore包,这将使用Entity Framework Core通过SQL Server来储存身份识别的数据和表信息。

Note

说明

In Visual Studio, you can view NuGet packages details by selecting Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution. You also see a list of packages in the dependencies section of the project.json file within your project.

在VS中,你可以逐一选择Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution浏览NuGet包的细节。也会看到项目的project.json文件的Dependencies部分看到该包的清单。

The identity services are added to the application in the ConfigureServices method in the Startup class:

身份识别功能位于Startup类的ConfigureServices方法中。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders(); services.AddMvc(); // Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();

These services are then made available to the application through dependency injection.

这些服务通过依赖注入起作用。

Identity is enabled for the application by calling UseIdentity in the Configure method of the Startup class. This adds cookie-based authentication to the request pipeline.

通过调用Startup类Configure方法中的UseIdentity启用身份识别。这样,对于访问请求就可通过cookie实现身份验证了。

    services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = ;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false; // Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();
options.Lockout.MaxFailedAccessAttempts = ; // Cookie settings
options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays();
options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
options.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOff";
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}

For more information about the application start up process, see Application Startup.

  1. Creating a user.

2. 创建用户

Launch the application from Visual Studio (Debug -> Start Debugging) and then click on the Register link in the browser to create a user. The following image shows the Register page which collects the user name and password.

When the user clicks the Register link, the UserManager and SignInManager services are injected into the Controller:

当用户点击Register链接时,UserManager和SignInManager服务就被注入到控制器中:

    public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private static bool _databaseChecked;
private readonly ILogger _logger; public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
} //
// GET: /Account/Login

Then, the Register action creates the user by calling CreateAsync function of the UserManager object, as shown below:

接着,Register动作通过调用UserManager对象的CreateAsync函数函数创建了用户,具体如下:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(, "User created a new account with password.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
AddErrors(result);
} // If we got this far, something failed, redisplay form
return View(model);
}
  1. Log in.

3.登陆

If the user was successfully created, the user is logged in by the SignInAsync method, also contained in the Register action. By signing in, the SignInAsync method stores a cookie with the user’s claims.

如果成功创建了用户,就会使用SignInAsync方法实现用户登录,该方法同样包含在Register动作中。通过签到后,SignInAsync方法使用用户的登陆信息存储了一个cookie。

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(, "User created a new account with password.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
AddErrors(result);
} // If we got this far, something failed, redisplay form
return View(model);
}

The above SignInAsync method calls the below SignInAsync task, which is contained in the SignInManager class.

上面的SignInasync方法调用了下面的SignInAsync任务,该任务包含在SingInManager类中。

If needed, you can access the user’s identity details inside a controller action. For instance, by setting a breakpoint inside the HomeController.Index action method, you can view the User.claims details. By having the user signed-in, you can make authorization decisions. For more information, see Authorization.

如果需要,你可以深入控制器动作中用户身份识别的细节。比如说,通过在HomeController.Index方法中设置断点,就可以浏览User.Claims的细节。通过用户登录,就可以实现权限策略。

As a registered user, you can log in to the web app by clicking the Log in link. When a registered user logs in, the Login action of the AccountController is called. Then, the Login action signs in the user using the PasswordSignInAsync method contained in the Login action.

作为注册用户,你可通过点击Log in链接登陆应用。当注册用户登陆时,就调用AccountController中的Login动作。接着,Login动作使用其中的PasswordSignInAsync方法实现用户签到。

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
} // If we got this far, something failed, redisplay form
return View(model);
}
  1. Log off.

4.登出

Clicking the Log off link calls the LogOff action in the account controller.

点击Log off链接调用账户控制其中的Logoff方法。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}

The code above shows the SignInManager.SignOutAsync method. The SignOutAsync method clears the users claims stored in a cookie.

上面显示了SignInManager.SignOutAsyce方法中的代码。SignOutAsync方法清除存储在cookie中的用户登录信息。

  1. Configuration.

5.配置

Identity has some default behaviors that you can override in your application’s startup class.

身份识别具有一些默认的行为,你也可以在应用的startup类中将其重写。

    // Configure Identity
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = ;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false; // Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();
options.Lockout.MaxFailedAccessAttempts = ; // Cookie settings
options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays();
options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
options.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOff";
});
  1. View the database.

6. 浏览数据库

After stopping the application, view the user database from Visual Studio by selecting View -> SQL Server Object Explorer. Then, expand the following within the SQL Server Object Explorer:

  • (localdb)MSSQLLocalDB
  • Databases
  • aspnet5-<the name of your application>
  • Tables

Next, right-click the dbo.AspNetUsers table and select View Data to see the properties of the user you created.

Identity Components 身份识别的组成

The primary reference assembly for the identity system is Microsoft.AspNetCore.Identity. This package contains the core set of interfaces for ASP.NET Core Identity.

身份系统主要的引用文件包为Microsoft.AspNetCore.Identity 。其中包含了ASP.NET Core Identity的系列核心界面。

These dependencies are needed to use the identity system in ASP.NET Core applications:

需要引用ASP.NET Core中的identity system来实现这些功能。

  • EntityFramework.SqlServer - Entity Framework is Microsoft’s recommended data access technology for relational databases.
  • Microsoft.AspNetCore.Authentication.Cookies - Middleware that enables an application to use cookie based authentication, similar to ASP.NET’s Forms Authentication.
  • Microsoft.AspNetCore.Cryptography.KeyDerivation - Utilities for key derivation.密钥导出的实用程序
  • Microsoft.AspNetCore.Hosting.Abstractions - Hosting abstractions.托管逻辑

Migrating to ASP.NET Core Identity

For additional information and guidance on migrating your existing identity store see Migrating Authentication and Identity

关于迁移已有的身份识别数据,请参看Migrating Authentication and Identity

Next Steps

原文链接

ASP.NET Core身份识别的更多相关文章

  1. ASP.NET Core身份验证

    asp.net core 身份验证 本文旨在演示如果使用内置的 identity 实现 asp.net core 的身份验证,不会进行其它扩展.本文将通过最简单的代码演示如何进行登录和身份验证操作. ...

  2. 深入解读 ASP.NET Core 身份认证过程

    长话短说:上文我们讲了 ASP.NET Core 基于声明的访问控制到底是什么鬼? 今天我们乘胜追击:聊一聊ASP.NET Core 中的身份验证. 身份验证是确定用户身份的过程. 授权是确定用户是否 ...

  3. ASP.NET Core 身份验证(一)

    前言 这篇文章我想带领大家了解一下 ASP.NET Core 中如何进行的身份验证,在开始之前强烈建议还没看过我写的 Identity 系列文章的同学先看一下. Identity 入门系列文章: Id ...

  4. ASP.NET Core 身份认证 (Identity、Authentication)

    Authentication和Authorization 每每说到身份验证.认证的时候,总不免说提及一下这2个词.他们的看起来非常的相似,但实际上他们是不一样的. Authentication想要说明 ...

  5. ASP.NET Core身份验证服务框架IdentityServer4-整体介绍

    一.整体情况 现代应用程序看起来更像这个: 最常见的相互作用: 浏览器与Web应用程序的通信 Browser -> Web App Web应用程序与Web API通信 基于浏览器的应用程序与We ...

  6. ASP.NET Core身份认证服务框架IdentityServer4(2)-整体介绍

    一.整体情况 现代应用程序看起来更像这个: 最常见的相互作用: 浏览器与Web应用程序的通信 Browser -> Web App Web应用程序与Web API通信 基于浏览器的应用程序与We ...

  7. asp.net core 身份认证/权限管理系统简介及简单案例

    如今的网站大多数都离不开账号注册及用户管理,而这些功能就是通常说的身份验证.这些常见功能微软都为我们做了封装,我们只要利用.net core提供的一些工具就可以很方便的搭建适用于大部分应用的权限管理系 ...

  8. ASP.NET Core身份认证服务框架IdentityServer4 介绍

    IdentityServer4是ASP.NET Core 2的OpenID Connect和OAuth 2.0框架.它可以在您的应用程序中提供以下功能: 它使你的应用程序具有如下特点: 认证即服务 适 ...

  9. .NET 黑魔法 - asp.net core 身份认证 - Policy

    身份认证几乎是每个项目都要集成的功能,在面向接口(Microservice)的系统中,我们需要有跨平台,多终端支持等特性的认证机制,基于token的认证方式无疑是最好的方案.今天我们就来介绍下在.Ne ...

随机推荐

  1. 软件密码和https协议

    密码安全问题,一直是程序员最痛疼的问题,这一章主要的来说一下密码的安全,和怎么提高密码的安全,还有Tomcat的https协议. 密码对于一个程序的安全有多重要就不多说了,如果你做过银行系统的话,那么 ...

  2. RabbitMQ术语

    工作队列:Working Queue 分配:多个客户端接收同一个Queue,如何做负载均衡(分配).     Round-robin分配:多个接收端接收同一个Queue时,采用了Round-robin ...

  3. vim基本使用

    i 进入插入状态 esc 退出插入状态 x 删除一个字符 dd 删除一行,并拷贝 yy 拷贝 p 粘贴 u 撤销 ctrl+r 重做 :w 保存 :q 退出 :q! → 退出不保存

  4. Spring源码之SimpleAliasRegistry解读(一)

    Spring源码之SimpleAliasRegistry解读(一) 阅读spring源码中org.springframework.core.SimpleAliasRegistry类时发现该类主要是使用 ...

  5. VC++ 监控指定目录改变

    转载:http://www.cnblogs.com/doublesnke/archive/2011/08/16/2141374.html VC++实施文件监控:实例和详解 相关帮助: http://h ...

  6. HP QC IE11不支持( win7 64位 无法安装)解决方法

    QC IE11不支持( win7 64位 无法安装)解决方法 使用HP公司的QC做项目缺陷管理,发现IE浏览器只支持IE7,IE8.安装插件ALP_Platform_Loader提示64位无法安装,顿 ...

  7. Populate A List Item With Record Group In Oracle Forms Using Populate_List And Create_Group_From_Query Command

    Example is given below to Populate a List Item in Oracle Forms using Create_Group_From_Query , Popul ...

  8. 统计fastq文件中读段的数量

    mycount=`cat SRR108114_new_1.fastq | wc -l` echo 'Number of clean reads, SRR108114_new_1.fastq: '$(( ...

  9. Django 过滤器 实例

    实例1 safe让Html标签以及一些特殊符号(如<)生效,下面以例子说明: # value = '<b>CPT</b>' # 那么输出的时候,CPT就是加粗的,如果不加 ...

  10. Cookie 总结

    设置Cookie //设置cookie Cookie cookie = new Cookie("TOM","111"); //设置有效期,默认秒为单位 cook ...