[mvc] 簡單的forms認證

一、在web.config的system.web節點增長authentication節點,定義以下:html

  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880">
        <credentials passwordFormat="Clear">
          <user name="user" password="pwd001"/>
          <user name="admin" password="pwd002"/>
        </credentials>
      </forms>
    </authentication>
  </system.web>

2,新增AccountController。web

    public class AccountController : Controller
    {
        // 用於初期表示用
        public ActionResult Login()
        {
            return View();
        }

        // 登陸按鈕
        [HttpPost]
        public ActionResult Login(string username, string password, string returnUrl)
        {
            bool result = FormsAuthentication.Authenticate(username, password);
            if (result)
            {
                FormsAuthentication.SetAuthCookie(username, false);
                return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
            }
            else
            {
                ModelState.AddModelError("", "Incorrect username or password");
                return View();
            }
        }
    }

三、Login.cshtml瀏覽器

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        <p><label>Username:</label><input name="username" type="text" /></p>
        <p><label>Password:</label><input name="password" type="password" /></p>
        <input type="submit" value="Log in"/>
    }
</body>
</html>

四、瀏覽器輸入http://localhost:44324/Account/Login,輸入web.config中定義的用戶名和密碼,成功就會進入Admin/Index頁面。spa

五、其餘頁面如何進行認證?debug

1)在action中加Request.IsAuthenticated判斷code

    public class AdminController : Controller
    {
        // GET: Admin
        public string Index()
        {
            if (!Request.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }
            return "welcome to Admin page!";
        }
    }

2)在action方法上加Authorize特性orm

    public class AdminController : Controller
    {
        // GET: Admin
        [Authorize]
        public string Index()
        {
            return "welcome to Admin page!";
        }
    }

3)在controller上加Authorize特性(全部的action都會應用上)htm

    [Authorize]
    public class AdminController : Controller
    {
        // GET: Admin
        public string Index()
        {
            return "welcome to Admin page!";
        }
    }
相關文章
相關標籤/搜索