Introduction to Identity

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 Identity是一个成员系统,允许在应用中添加登陆功能。用户可新建账户并使用用户名和密码登陆,或者使用外部登陆提供者登陆,例如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 Identity从而使用SQL Server数据库储存用户名、密码和配置信息。或者使用例如Azure Table Storage等其他的存储方式。

Overview of Identity 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 Identity添加功能,实现用户的注册、登陆、注销。你可一步一步地跟着学习,或者仅阅读其中的细节。关于使用ASP.NET Identity更多的细节,请参看本文中的Next Steps中列出的文章。

  1. Create an ASP.NET Core Web Application project in Visual Studio with Individual 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.

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

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 packages的细节。你也可在项目中的project.json文件中dependencies部分看到引用包的列表

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

Identity服务被加入到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方法中的UserIdentity就可以使用Identity了。这为请求添加了基于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"; // User settings
options.User.RequireUniqueEmail = true;
});
} // 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();

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

更多关于应用启动过程的信息,请参看Application Startup。

  1. Creating a user. 新建用户

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:

然后,通过调用UserManager类中的CreateAsync函数,Register新建了该用户,如下所示:

[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. 登陆

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任务,该任务包含在SignInManager类中。

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的细节信息。你可搭建授权决策。更多的信息,请参看Authorization

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. 登出

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

[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.SignOutAsync 方法。SignOutAsync方法清楚了cookie中的用户声明。

  1. Configuration. 配置

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

Identity有一些默认的行为,你可以在应用的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"; // User settings
options.User.RequireUniqueEmail = true;
});
  1. View the database.

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:

关闭应用后,在VS中通过选择View -> SQL Server Object Explorer 浏览用户数据库。然后,在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.

接下来,右击dbo.AspNetUsers表,并选择View Data查看你新建的用户属性。

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的应用中要使用身份系统,这些附加功能是必须的:

  • 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

迁移ASP.Net Core Identity

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

Security » Authentication » Identity介绍的更多相关文章

  1. Spring Security核心概念介绍

    Spring Security是一个强大的java应用安全管理库,特别适合用作后台管理系统.这个库涉及的模块和概念有一定的复杂度,而大家平时学习Spring的时候也不会涉及:这里基于官方的参考文档,把 ...

  2. Hadoop Security Authentication Terminology --Kerberos

    Hadoop Security Authentication Terminology --Kerberos What is kinit? Kinit -  obtain and cache Kerbe ...

  3. asp.net core系列 46 Identity介绍

    一. Identity 介绍 ASP.NET Core Identity是一个会员系统,可为ASP.NET Core应用程序添加登录功能.可以使用SQL Server数据库配置身份以存储用户名,密码和 ...

  4. 报错:Sqoop2 Exception: java.lang.NoSuchMethodError Message: org.apache.hadoop.security.authentication.client.Authenticator

    报错过程: 进入sqoop2之后, 输入命令:show connector,报错 报错现象: Exception has occurred during processing command Exce ...

  5. Phoenix 5.0 hbase 2.0 org.apache.hadoop.security.authentication.util.KerberosUtil.hasKerberosKeyTab

    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...

  6. System.Security.Authentication.AuthenticationException:根据验证过程,远程证书无效。

    好久没写博客了,今天突然遇到个神奇的问题. 做好的网站在win10上和Windows sever 2012 上都没有问题,搬到Windows sever 2003上就出现了这么一个错误: Server ...

  7. Illegal reflective access by org.apache.hadoop.security.authentication.util.KerberosUtil

    在使用Java API操作HBase时抛出如下异常: Illegal reflective access by org.apache.hadoop.security.authentication.ut ...

  8. 基于SAML2.0的SAP云产品Identity Authentication过程介绍

    SAP官网的架构图 https://cloudplatform.sap.com/scenarios/usecases/authentication.html 上图介绍了用户访问SAP云平台时经历的Au ...

  9. asp.net identity 介绍

    Asp.Net Identity 设计目标 微软在 asp.net 2.0 引入了 membership,为 asp.net 应用程序提供身份验证和授权功能.membership 假定用户在网站注册, ...

随机推荐

  1. LeetCode Strobogrammatic Number II

    原题链接在这里:https://leetcode.com/problems/strobogrammatic-number-ii/ 题目: A strobogrammatic number is a n ...

  2. Windows平台配置免安装的MySQL

    1.下载 官网下载免安装文件(本文使用的是mysql-5.6.33-win32.zip)解压到E:\MySQL\mysql-5.6.33打开E:\MySQL\mysql-5.6.33\my-defau ...

  3. 压缩文本、字节或者文件的压缩辅助类-GZipHelper 欢迎收藏

    压缩文本.字节或者文件的压缩辅助类-GZipHelper 欢迎收藏 下面为大家介绍一.NET下辅助公共类GZipHelper,该工具类主要作用是对文本.字符.文件等进行压缩与解压.该类主要使用命名空间 ...

  4. 小Q系列之 最佳裁判

    这个题需要注意一些数据条件 尤其是一些输入数据条件 #include<algorithm> #include<stdio.h> #include<math.h> u ...

  5. 用oop分析场景,写出代码。房间里,有人、猫、老鼠在睡觉,然后猫醒了发出叫声,叫声惊醒了人,人从床上坐起来,惊醒了老鼠,老鼠开始逃跑。

    首先分析有哪些类: 应该有房子.动物类.人类.猫类.老鼠类. 房子不仅仅是一个容器,因为猫在房子里叫,惊醒了人和老鼠,所以猫叫是一个事件,通过这个事件触发人和老鼠的惊醒. 可以定义一个委托,利用委托绑 ...

  6. csuoj 1503: 点到圆弧的距离

    http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1503 1503: 点到圆弧的距离 时间限制: 1 Sec  内存限制: 128 MB  Speci ...

  7. 手机触摸touch事件

    1.Touch事件简介 pc上的web页面鼠 标会产生onmousedown.onmouseup.onmouseout.onmouseover.onmousemove的事件,但是在移动终端如 ipho ...

  8. this的面面观

    http://www.cnblogs.com/Wayou/p/all-this.html <JavaScript语言精粹> 全局this 浏览器宿主的全局环境中, function f(x ...

  9. android架构

    周日没事,简单总结了一下Android开发中使用到的知识,以脑图的形式呈现.  

  10. 马哥教育视频笔记:01(Linux常用命令)

    1.查看缓存中使用的命令和命令路径 [wskwskwsk@localhost /]$ hash 命中 命令 /usr/bin/printenv /usr/bin/ls /usr/bin/clear 2 ...