** 步驟如下 **
第一,打開一個 ASP.NET Core 的 MVC專案
第二,透過 Nuget安裝「Microsoft.AspNetCore.Authentication.Cookies」
第三,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 ListClaim // 搭配 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
可以參閱這一則影片 ( [ASP.NET] )
public async TaskIActionResult Logout()
{
// 自己宣告 Microsoft.AspNetCore.Authentication.Cookies; 命名空間 await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return View(); // 回 首頁。 return RedirectToAction(“Index”, “Home”);
}