asp.net core系列 46 Identity介紹

一. Identity 介紹

  ASP.NET Core Identity是一個會員系統,可爲ASP.NET Core應用程序添加登陸功能。可使用SQL Server數據庫配置身份以存儲用戶名,密碼和配置文件數據。或者,可使用另外一個持久性存儲,例如,Azure表存儲。下面學習如何使用Identity註冊,登陸以及基架標識。html

  

  1.1 Identity搭建演示git

    下面使用vs 2017來演示:web

      1.選擇「文件」 > 「新建」 > 「項目」。sql

      2.選擇「ASP.NET Core Web應用程序」。 將項目命名WebAppIdentityDemo具備項目下載相同的命名空間。 單擊 「肯定」。數據庫

      3.選擇 ASP.NET Core Web MVC應用程序,而後選擇更改身份驗證。json

      4.選擇單個用戶賬戶而後單擊肯定。cookie

    生成的項目包含了Identity會員系統,目錄結構以下所示,生成後的目錄結構有疑惑,怎麼沒看見Identity會員系統相關的model, Controller,cshtml等文件,繼續往下了解。app

    (1) 修改鏈接字符串ide

      找到appsettings.json文件,修改ConnectionStrings的數據庫鏈接字符串, 默認是鏈接本機sql server數據庫,我改爲了鏈接遠程數據庫。佈局

"ConnectionStrings": {
    "DefaultConnection": "Data Source = 172.168.16.75;Initial Catalog =IdentityDB; User ID = hsr;Password =js*2015;"
  },

     (2) 基於生成的遷移代碼,同步到數據庫 

      PM> Update-Database 

    (3) 配置Identity服務

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity
<IdentityUser>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores<ApplicationDbContext>(); 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; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }

    (4) 確認調用UseAuthentication中間件

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

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
  app.UseAuthentication();
    app.UseMvc();
}

     (5) 啓動程序,首頁提供了註冊,登陸的連接

      註冊成功後/Identity/Account/Register,在數據庫中AspNetUsers表會新增一條數據(密碼:Asp.netCore123)。註冊成功後,說明數據庫鏈接沒有問題,會跳到登陸頁Identity/Account/Login

      雖然沒有看到Identity會員系統相關文件,其實已經內置由Razor類庫提供。Identity Razor類庫使用該Identity Areas公開端點。例如:

             /Identity/Account/Login

             /Identity/Account/Logout

             /Identity/Account/Manage

  

二. 基架標識(Scaffold Identity )

  ASP.NET Core 2.1 及更高版本提供了ASP.NET Core Identity做爲Razor 類庫。 包含Identity的應用程序能夠應用基架,來有選擇地添加包含在Identity Razor 類庫 (RCL) 的源代碼。 建議生成源代碼,以便修改代碼和更改行爲(根據開發需求擴展Identity)。 例如,能夠指示基架生成在註冊過程當中使用的代碼。 生成的代碼優先於標識 RCL 中的相同代碼。 若要獲取的用戶界面的徹底控制,而且使用默認 RCL,等下參考2.2。      

   

  2.1 使用Scaffold Identity 受權到MVC 項目

      1.從解決方案資源管理器,右鍵單擊該項目 >添加 > 新基架項。

      2.從左窗格添加基架對話框中,選擇標識 > 添加。

      3.在中ADD 標識添加對話框中,選擇所需的選項。

    下面使用現有的數據上下文,選擇全部文件,以便後面重寫,以下所示。

    生成須要重寫的文件後,以下所示(能夠比對上圖1.1的Areas目錄),注意生成的是razor page 文件,不是MVC視圖控制器。以前上面的疑惑解除了。

    

  2.2 建立完整的Identity UI 源

   上面2.1中運行Scaffold Identity,保持了對Identity UI的徹底控制。如下突出顯示的代碼顯示默認Identity UI 替換Identity在 ASP.NET Core 2.1 web 應用的更改。 須要執行此操做以具備徹底控制權限的Identity  UI。

    public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<IdentityUser, IdentityRole>()
            //services.AddDefaultIdentity<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            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;
            //});

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

                options.LoginPath = $"/Identity/Account/Login";
                options.LogoutPath = $"/Identity/Account/Logout";
                options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
            });

            // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddRazorPagesOptions(options =>
                {
                    options.AllowAreas = true;
                    options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                    options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout"); });
        }

     選擇修改Login.cshtml文件,在裏面隨變加點標記xxxx, 運行顯示成功,之後就能夠自定義樣式佈局和擴展權限功能。

 

     

   參考文獻

   ASP.NET Core 上的Identity簡介

   ASP.NET Core 項目中的scaffold-identity

相關文章
相關標籤/搜索