[ASP.NET MVC][Owin] 用最簡單 Cookie 認證方式

  • 4544
  • 0

上一次簡單提到 [ASP.NET] Forms 驗證與授權 的方式,

這次改換 Owin 的 Microsoft.Owin.Security.Cookies 如何做驗證與授權,

  1. 記得 web.config 內 <system.web> 的 authentication 別使用 Forms
  2. 記得得參考 Owin 組件
  3. 在 Package Manager Console 執行 Install-Package Microsoft.Owin.Security.Cookies
  4. 在 Startup 類別的 Configuration 加上使用 CookieAuthentication 的方式,並在這邊做設定或事件的註冊,
    其中 AuthenticationType 是非常重要的,一定要指定,而且在登入方法那邊也需相同 AuthenticationType:
  5.     public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = "MyCookieName",
                    LoginPath = new PathString("/Default/Index"),
                    ExpireTimeSpan = TimeSpan.FromMinutes(5)
                });
            }
        }

     

  6.  最簡單的登入登出範例,主要建立一個 ClaimsIdentity 用來辨識驗證身分的Name, Role之類的,
    用 HttpRequestBase 的擴充方法 GetOwinContext 取得 Owin Context,
    就能用屬性 Authentication 的 SignIn 方法來做登入:
  7.         [HttpPost]
            public ActionResult SignIn()
            {
                var claims = new[] {
                    new Claim(ClaimTypes.Name, "myname"),
                    new Claim(ClaimTypes.Email, "myemail@gmail.com"),
                    // can add more claims
                };
                var identity = new ClaimsIdentity(claims, "MyCookieName");
    
                Request.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, identity);
                return RedirectToAction("Index");
            }
    
            [HttpPost]
            public ActionResult Logout()
            {
                Request.GetOwinContext().Authentication.SignOut();
                return RedirectToAction("Index");
            }

     

  8.  想授權哪個 Controller 或 Action 的方式一樣沒變,例如
            // GET: Setting
            [Authorize]
            public ActionResult Index()
            {
                return View();
            }

     

參考文章:

Understanding OWIN Forms authentication in MVC 5