ASP.NET Core 验证:(二)介绍ASP.NET Core的 Indentity

ASP.NET Core 的身份(Identity):

  • 是一套支持用户界面登录功能的API。
  • 其可以管理用户,密码,配置数据,角色,声明,凭证,邮件确认,以及更多信息。

用户可以使用存储在Identity中的登录信息来创建一个账户,或者也可以使用外部的登录提供器。支持的外部登录提供器包括 Facebook,Google,Microsoft Account,and Twitter

Identity的源代码在github上是开源的,具体可以查看此链接:Identity source code。我们可以使用基架来生成Identity并查看生成的文件,以此来查看生成的模板是如何与Identity交互的。

通常情况下,Identity被配置为使用SQL Server 数据库来存储用户名,密码以及配置数据。作为一个替代方案,另一种持久化存储技术也可以被使用,比如说 Azure Table Storage。

在本章中,你将学习如何使用Identity 来注册,登录以及登出一个用户。关于创建一个使用Identity 的app的更多详细的指导,请看本章节结尾的 “下一步”的内容。

微软身份平台是(Microsoft Identity Platform):

  •  一个Azure Active Directory (Azure AD) 开发者平台的等价物。
  • 与ASP.NET Core Identity无关。

ASP.NET Core Identity 为ASP.NET Core web app添加了用户界面登录功能。为了保证APIs 和 SPAs的安全,使用如下之一的技术:

IdentityServer4是一个OpenID Connct 以及OAuth 2.0 框架,其服务于ASP.NET Core 3.0。IdentityServer4 启用了如下安全特性:

  • Authentication as a Service (AaaS)
  • Single sign-on/off (SSO) over multiple application types
  • Access control for APIs
  • Federation Gateway

更多信息,请查看Welcome to IdentityServer4

创建一个带有验证功能的Web app

步骤:

  • 选择 文件 > 新建 > 工程。
  • 选择 ASP.NET Core web 应用程序。将工程命名为WebApp1 以具有和下载的工程相同的命名空间。点击 OK。
  • 选择一个ASP.NET Core Web 应用程序,然后选择,更改验证方式。
  • 选择 个人用户账户,然后点击 OK。

生成的工程以Razor类库的方式提供了ASP.NET Core Identity 的功能。Identity Razor类库暴漏了带有Identity区域的终结点。举个例子:

  • /Identity/Account/Login
  • /Identity/Account/Logout
  • /Identity/Account/Manage

应用迁移文件

       需要应用Migration 特性来初始化所需的数据库。在包管理器控制台中运行如下命令:Update-Database。

测试注册以及登录

       运行app并且注册一个用户,取决于你的屏幕大小,你或许需要选择导航拖动按钮来查看 Register 和  Login 链接。

查看Identity数据库

      可以通过SSMS来查看生成的数据库。

配置Identity服务

       服务在ConfigureServices 中被添加。典型的模式是调用所有的Add{Service} 方法,然后再调用所有的services.Configure{Service} 方法。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddRazorPages();

    services.Configure<IdentityOptions>(options =>
    {
        // Password settings.
        options.Password.RequireDigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = true;
        options.Password.RequireUppercase = true;
        options.Password.RequiredLength = 6;
        options.Password.RequiredUniqueChars = 1;

        // Lockout settings.
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.AllowedForNewUsers = true;

        // User settings.
        options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
        options.User.RequireUniqueEmail = false;
    });

    services.ConfigureApplicationCookie(options =>
    {
        // Cookie settings
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

        options.LoginPath = "/Identity/Account/Login";
        options.AccessDeniedPath = "/Identity/Account/AccessDenied";
        options.SlidingExpiration = true;
    });
}

       前面高亮显示的代码用默认选项值配置了Identity。服务通过DI使得其在整个app内都是可用的。通过调用UseAuthentication 来启用Identity。UseAuthentication向请求管道中加入验证中间件。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

这个基于模板生成的app不会使用授权。之所以包含UseAuthorization是为了确保其以正确的顺序被添加。UseRoutingUseAuthenticationUseAuthorization, 以 UseEndpoints 必须被以如上所示的顺序被添加。

关于IdentityOptions 和 Startup的更多信息,请参考 IdentityOptions 和 Application Startup

Identity 组件

       所有依赖于Identity的NuGet包都包含在  ASP.NET Core shared framework中。对Identity来说最主要的包是 Microsoft.AspNetCore.Identity。这个包包含了ASP.NET Core Identity 的核心接口集合。其被包含在Microsoft.AspNetCore.Identity.EntityFrameworkCore中。

迁移至ASP.NET Core Identity

       关于迁移你现存的Identty存储的更多信息及指导,请参考 Migrate Authentication and Identity

设置密码强度

       查看 Configuration,以获取设置最小密码需求的示例。

AddDefaultIdentity 和 AddIdentity

AddDefaultIdentity 在ASP.NET Core 2.1被引入。调用AddDefaultIdentity 类似于调用如下方法:  

查看AddDefaultIdentity source 以获取更多信息。

避免发布静态Identity资产

       为了避免发布静态Identity资产到 Web root,向app 工程文件添加ResolveStaticWebAssetsInputsDependsOn属性以及RemoveIdentityAssets目标。

<PropertyGroup>
  <ResolveStaticWebAssetsInputsDependsOn>RemoveIdentityAssets</ResolveStaticWebAssetsInputsDependsOn>
</PropertyGroup>

<Target Name="RemoveIdentityAssets">
  <ItemGroup>
    <StaticWebAsset Remove="@(StaticWebAsset)" Condition="%(SourceId) == 'Microsoft.AspNetCore.Identity.UI'" />
  </ItemGroup>
</Target>

下一步      

原文地址:https://www.cnblogs.com/qianxingmu/p/12797302.html