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

2020/02/04閱讀時間約 11 分鐘

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

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
或是參考我錄製的教學影片 — https://youtu.be/eRa-hdsDfB4
微軟的文件(中文) .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

** 步驟如下 **

第一,打開一個 ASP.NET Core 的 MVC專案
第二,透過 Nuget安裝「Microsoft.AspNetCore.Authentication.Cookies
(3–1) ConfigureServices這個區域,請加入這兩段
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
 .AddCookie();


(3–2) Configure這個區域,請加入這兩段
app.UseAuthentication(); // 這一句話需要手動加入,後面幾句是原本就有的
 app.UseAutho
rization();
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
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線上教學的朋友,可以發現跟原本範例的差異不大
 主要是上述(第四部分)的修改而已。

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

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小時 完整內容 免費試聽,請看

為什麼會看到廣告
    2會員
    113內容數
    留言0
    查看全部
    發表第一個留言支持創作者!