[mvc] Simple forms authentication

1. Add the authentication node to the system.web node of web.config, which is defined as follows:

  <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。

    public class AccountController : Controller
    {
        // Use 
        public ActionResult Login() for initial presentation
        {
            return View();
        }

        // Login button 
        [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();
            }
        }
    }

3、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>

4. Enter http://localhost:44324/Account/Login in the browser, enter the username and password defined in web.config, and successfully enter the Admin/Index page.

5. How to authenticate other pages?

1) Add Request.IsAuthenticated judgment to action

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

2) Add the Authorize feature to the action method

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

3) Add the Authorize feature to the controller (all actions will be applied)

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325739803&siteId=291194637