asp.net core系列 46 Identity介紹


一. Identity 介紹

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

  

  1.1 Identity搭建演示

    下面使用vs 2017來演示:

      1.選擇“文件” > “新建” > “項目”。

      2.選擇“ASP.NET Core Web應用程序”。 將項目命名WebAppIdentityDemo具有項目下載相同的命名空間。 單擊 “確定”。

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

      4.選擇單個用戶帳戶然后單擊確定。

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

    (1) 修改連接字符串

      找到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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM