[ASP.NET Core] 最簡單 Cookie 認證與授權的範例

  • 4085
  • 0
  • 2016-11-18

上一篇提到 [ASP.NET MVC][Owin] 用最簡單 Cookie 認證方式

這次改換 ASP.NET Core 的 Microsoft.AspNetCore.Authentication.Cookies 練習最簡單的 Cookie 認證與授權,

  1. 在 project.json 的 dependencies 加入
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0"

    並記得每次加完要進行套件還原(Visual Studio 會自動套件還原),自己寫指令則到專案目錄下,用 Command Line 輸入 dotnet restore 手動還原

  2.  在 Startup 類別的 Configuration 加上使用 CookieAuthentication 的方式
               app.UseCookieAuthentication(new CookieAuthenticationOptions()
                {
                    AuthenticationScheme = "MyCookieMiddlewareInstance",
                    LoginPath = new PathString("/Test/Index/"),
                    AutomaticAuthenticate = true,
                    AutomaticChallenge = true
                });

    CookieAuthenticationOption 的屬性可參考官網說明,在最下方會提供參考連結

  3. 最簡單的登入範例,很重要的是 ClaimsIdentity 建構式第二個參數是 authenticationType 一定要填,不然驗證沒有作用 Http Response Hreaders 也不會有 Set-Cookie

            public async Task<IActionResult> Login()
            {
                var claims = new List<Claim>() {
                    new Claim(ClaimTypes.Name, "Herry"),
                    new Claim(ClaimTypes.Role, "Users")
                };
                var claimsIdentity = new ClaimsIdentity(claims, "myTest");
                var principal = new ClaimsPrincipal(claimsIdentity);
                await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal);
    
                return Ok();
            }

     

  4. 想授權哪個 Controller 或 Action 的方式一樣沒變,例如
            [Authorize]
            public IActionResult Index()
            {
                return View();
            }
     

參考文章

Using Cookie Middleware without ASP.NET Core Identity