網站結構
webconfig
設定為form驗證, 並拒絕所有的匿名使用者
<authentication mode="Forms">
<forms loginUrl="~/Account/Index" timeout="2880" path="/" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
如果我們徐凱開放首頁比如說Home/Index,那麼做如下配置. 如果是Home檔案夾下所有的頁面都能訪問, 那麼 path=”Home”即可
<location path="Home/Index">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
cookie
啟動程式, 來到登入頁面. 如果登入成功, 那麼我們需要寫入cookie.
登陸頁面
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<mvc安全驗證.Models.User>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<% using( Html.BeginForm()){%>
登入
<%: Html.TextBoxFor(m => m.UserName, new { @class = "log" })%>
<%: Html.TextBoxFor(x => x.RealName) %><br />
<input type="submit" value="login" />
<%};%>
</div>
</body>
</html>
處理方法
[HttpPost]
public ActionResult Index(Models.User model) {
if (model.UserName == "admin")
{
//創造票據
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(model.UserName, false, 1);
//加密票據
string ticString = FormsAuthentication.Encrypt(ticket);
//輸出到用戶端
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));
//跳轉到登入前頁面
return Redirect(HttpUtility.UrlDecode( Request.QueryString["ReturnUrl"]));
}
return View();
}
退出.通過 new FormsAuthenticationTicket(model.UserName, false, 時間長度); 設定.AXPXAUTH到期時間長度. 但是如果new HttpCookie(FormsAuthentication.FormsCookieName, ticString) 這個cookie對象沒有設定到期時間, 那麼上面設定的時間長度再長, cookie的生命週期還是瀏覽器的生命週期.
public ActionResult Logout() {
FormsAuthentication.SignOut();
return Redirect(FormsAuthentication.LoginUrl);
}
這樣, 在預設首頁 home/index 中可以得到
八卦一下. User的值是在哪裡獲得的呢?我們載入進來一個DLL, 自訂的httpmodulehttp://www.cnblogs.com/jianjialin/archive/2011/06/14/2080880.html
跟蹤一下. 發現在application_AuthenticateRequest事件裡面, 我們可以獲得User對象了.
代碼下載: 群共用搜尋 mvc安全驗證