[會員登入] 不使用ASP.NET Core Identity 的 Cookie 驗證 (ClaimsIdentity)

ASP.NET Core 3.1與 2.x 搭配 System.Security.Claims 命名空間的 ClaimsIdentity來做

輕鬆簡單,很快就能上手。Forms Authentication with cookie

使用沒有 ASP.NET Core 身分識別的 cookie 驗證(不使用ASP.NET Core Identity的 cookie 驗證)

<!-- google_ad_client = "ca-pub-0412737137097864"; /* 728x90 */ google_ad_slot = "2295073474"; google_ad_width = 728; google_ad_height = 90; //--> 

ASP.NET Core 3.1與 2.x ,搭配 System.Security.Claims 命名空間 的 ClaimsIdentity來做


我建議先閱讀這一篇文章,簡短有力,淺顯易懂。完成以後,再來看微軟官方說明。

(2018/8/2)  Forms Authentication in .NET Core (AKA Cookie Authentication)
http://www.nogginbox.co.uk/blog/forms-authentication-in-net-core-aka-cookie-authentication

微軟的文件(中文) .NET Core 2.1與 3.1差異不大。

但 3.1版的範例採用 Razor Page來示範。
https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/security/authentication/cookie/samples/3.x/CookieSample

每一個檢視畫面(網頁)跟以前WebForm(.aspx)一樣,分成兩個檔案(.cshtml 與 .cshtml.cs)。

我覺得比較不好懂。所以建議參閱 .NET Core 2.1的範例。
https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/security/authentication/cookie/samples/2.x/CookieSample

 

Youtube影片  https://youtu.be/eRa-hdsDfB4

 

** 步驟如下 **

第一,打開一個 ASP.NET Core 的 MVC專案

第二,透過 Nuget安裝「Microsoft.AspNetCore.Authentication.Cookies

第三,Startup.cs裡面有些設定:
請參閱  https://github.com/aspnet/AspNetCore.Docs/blob/master/aspnetcore/security/authentication/cookie/samples/3.x/CookieSample/Startup.cs

(3-1) ConfigureServices這個區域,請加入這兩段
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
           .AddCookie();
           
(3-2) Configure這個區域,請加入這兩段
            app.UseAuthentication();   // 這一句話需要手動加入,後面幾句是原本就有的
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                // endpoints.MapRazorPages();   // 如果您不使用 RazorPage來做,這一句可以註解掉、不用
            });


第四,HomeController控制器,您需要加入這些命名空間

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;    // Claims會用到
using Microsoft.AspNetCore.Authorization;  

(4-1) Login登入,輸入帳號、密碼。
        public IActionResult Login()
        {
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]   
        public ActionResult Login(db_user _User)  
        {

            if (ModelState.IsValid)
            {   // 入門版,先不連結DB,固定帳號密碼來做(微軟範例也是這樣)
                // 線上課程 裡會有連結資料庫,比對帳號與密碼的教材。  初學者不要急,一步一步學習。
                if (_User.UserName != "123" && _User.UserPassword != "123")
                {
                    ViewData["ErrorMessage"] = "帳號與密碼有錯";
                    return View();
                }

                #region ***** 不使用ASP.NET Core Identity的 cookie 驗證 *****
                var claims = new List<Claim>   // 搭配 System.Security.Claims; 命名空間
                {
                    new Claim(ClaimTypes.Name, _User.UserName),
                    // new Claim(ClaimTypes.Role, "Administrator"),
                    // 如果要有「群組、角色、權限」,可以加入這一段
                };

                // 底下的 ** 登入 Login ** 需要下面兩個參數 (1) claimsIdentity  (2) authProperties
                var claimsIdentity = new ClaimsIdentity(
                                           claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties
                {
                    //AllowRefresh = <bool>,
                    // Refreshing the authentication session should be allowed.

                    //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10), 
                    // The time at which the authentication ticket expires. A 
                    // value set here overrides the ExpireTimeSpan option of 
                    // CookieAuthenticationOptions set with AddCookie.

                    //IsPersistent = true,
                    // Whether the authentication session is persisted across 
                    // multiple requests. When used with cookies, controls
                    // whether the cookie's lifetime is absolute (matching the
                    // lifetime of the authentication ticket) or session-based.

                    //IssuedUtc = <DateTimeOffset>,
                    // The time at which the authentication ticket was issued.

                    //RedirectUri = <string>
                    // The full path or absolute URI to be used as an http redirect response value.
                };

                // *** 登入 Login *********
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                                        new ClaimsPrincipal(claimsIdentity),
                                                        authProperties);
                #endregion

                return Content("<h3>恭喜您,登入成功</h3>");
            }

            // Something failed. Redisplay the form.
            return View();
        }

(4-2) LogOut 登出。微軟範例以非同步(異步)的寫法來做 -- Async. Await

可以參閱這一則影片  https://youtu.be/8vcrjhaF1zE   ( [ASP.NET].NET 4.5 非同步程式,從一張圖知道原來如此 (async & await) )

        public async Task<IActionResult> Logout()
        {
            // 自己宣告 Microsoft.AspNetCore.Authentication.Cookies; 命名空間
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return View();  // 回 首頁。 return RedirectToAction("Index", "Home");
        }

 

** 範例下載 **

    我整理了一份 "PDF檔" 當作說明,也分享了這個範例
    專案名為 WebApplication2019_MVC_Core_LoginCookie

    這個範例為了搭配我的MVC課程,所以經過修改。
    已經購買 ASP.NET MVC 5線上教學的朋友,可以發現跟原本範例的差異不大
    主要是上述(第四部分)的修改而已。

請由此下載  https://onedrive.live.com/?id=6F7F668080F24B20%212586&cid=6F7F668080F24B20

***************************************************

ASP.NET MVC 5 線上教學(目前已經累積 75~80小時的課程)

課程大綱,請看 http://mis2000lab.pixnet.net/blog/post/35172535
或是  https://dotblogs.com.tw/mis2000lab/2018/08/14/aspnet_mvc_online_learning_mis2000lab


第一天 5.5小時 完整內容 免費試聽,請看

**  Youtube 免費觀賞 (1-1)  https://youtu.be/9spaHik87-A

**  Youtube 免費觀賞 (1-2)  https://youtu.be/BFkIFg1iFLo

 

購買完整MVC課程(一百小時),限時六折優惠並免費加贈兩萬元「.NET Core升級課程」,請直接來信洽詢

(太便宜!太划算,不能公開) mis2000lab (at) yahoo.com.tw ; school (at) mis2000lab.net

 

學員感言:

 

 

 

 

 

購買完整MVC課程(一百小時),限時六折優惠並免費加贈兩萬元「.NET Core升級課程」,請直接來信洽詢

(太便宜!太划算,不能公開) mis2000lab (at) yahoo.com.tw ; school (at) mis2000lab.net
 

 

我將思想傳授他人, 他人之所得,亦無損於我之所有;

猶如一人以我的燭火點燭,光亮與他同在,我卻不因此身處黑暗。----Thomas Jefferson

線上課程教學,遠距教學 (Web Form 約 51hr)  https://dotblogs.com.tw/mis2000lab/2016/02/01/aspnet_online_learning_distance_education_VS2015

線上課程教學,遠距教學 (ASP.NET MVC 約 135hr)  https://dotblogs.com.tw/mis2000lab/2018/08/14/ASPnet_MVC_Online_Learning_MIS2000Lab

 

寫信給我,不要私訊 --  mis2000lab (at) yahoo.com.tw  或  school (at) mis2000lab.net

 (1) 第一天 ASP.NET MVC5 完整影片(5.5小時 / .NET 4.x版)免費試聽。影片 https://youtu.be/9spaHik87-A 

 (2) 第一天 ASP.NET Core MVC 完整影片(3小時 / .NET Core 6.0~8.0)免費試聽。影片 https://youtu.be/TSmwpT-Bx4I 

[學員感言] mis2000lab課程評價 - ASP.NET MVC , WebForm  。 https://mis2000lab.medium.com/%E5%AD%B8%E5%93%A1%E6%84%9F%E8%A8%80-mis2000lab%E8%AA%B2%E7%A8%8B%E8%A9%95%E5%83%B9-asp-net-mvc-webform-77903ce9680b  


ASP.NET遠距教學、線上課程(Web Form + MVC)。 第一天課程, "完整" 試聽。 

.........   facebook社團   https://www.facebook.com/mis2000lab   ......................

.........  YouTube (ASP.NET) 線上教學影片  https://www.youtube.com/channel/UC6IPPf6tvsNG8zX3u1LddvA/

 

Blog文章 "附的範例" 無法下載,請看 https://dotblogs.com.tw/mis2000lab/2016/03/14/2008_2015_mis2000lab_sample_download

請看我們的「售後服務」範圍(嚴格認定)。

...................................................................................................................................................... 

ASP.NET MVC  => .NET Core MVC 線上教學  ...... 第一天課程 完整內容 "免費"讓您評估 / 試聽

[遠距教學、教學影片] ASP.NET (Web Form) 課程 上線了!MIS2000Lab.主講   事先錄好的影片,並非上課側錄!   觀看時,有如「一對一」面對面講課