[英]Custom Authentication and ASP.NET MVC
我有一個在ASP.NET 4
中構建的內部Web應用程序。 我們很難使用其他團隊構建的身份驗證API。 如果該站點的用戶已成功通過該站點的身份驗證,我希望他們可以訪問整個站點。
在ASP.NET
WebForm時代,我只是習慣在會話中保留自定義User對象。 如果該對象為null,我知道用戶未經過身份驗證。 在MVC
是否有類似但改進的方法。 如果可能的話,我不想構建自己的ASP.NET Membership模型提供程序。 這樣做最簡單的方法是什么?
您可以將Forms Authentication
與Authorize
attibute結合使用,如下所示,
要限制對視圖的訪問:
將AuthorizeAttribute屬性添加到操作方法聲明中,如下所示,
[Authorize]
public ActionResult Index()
{
return View();
}
在web.config中配置表單身份驗證
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
登錄發布操作:如果用戶有效,則設置身份驗證cookie
[HttpPost]
public ActionResult Login(User model, string returnUrl)
{
//Validation code
if (userValid)
{
FormsAuthentication.SetAuthCookie(username, false);
}
}
注銷動作:
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
您可能希望擁有自定義授權過濾器 。 這是一個例子: MVC中的自定義過濾器 。 然后,您可以在應用程序啟動時全局應用此過濾器(使用RegisterGlobalFilters
)。
public class LegacyAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (HttpContext.Current.Session["User"] == null)
base.HandleUnauthorizedRequest(actionContext);
}
}
然后在你的global.asax
你會有這樣的東西:
GlobalFilters.Filters.Add(new LegacyAuthorize());
你可以嘗試這樣的事情:
FormsAuthentication.SetAuthCookie(username, rememberMe);
要為經過身份驗證的用戶設置cookie,然后只需使用Controller或需要身份驗證的Action上的[Authorize]
屬性。
嘗試使用Google搜索該主題以獲取更多信息,您將在MVC中找到許多關於身份驗證和授權的內容。
您可以在MVC中執行的表單中執行的所有操作,只需在控制器登錄操作中設置會話變量即可。
或者你可以這樣做:在登錄操作中添加formsauthentication.setauthcookie("username")
在此之后,使用[Authorize]關鍵字的任何操作都將允許當前用戶進入。
您可以通過在登錄成功時簡單地放置會話變量值來執行會話身份驗證。 例如
public ActionResult Index(Models.Login login)
{
if (ModelState.IsValid)
{
Dal.Login dLogin = new Dal.Login();
string result = dLogin.LoginUser(login);
if (result == "Success")
Session["AuthState"] = "Authenticated";
}
return View();
}
現在的訣竅是,您應該擁有所有視圖的公共布局頁面,您必須檢查它們的身份驗證。 在這個布局頁面只需要像這樣做一個剃刀檢查 -
<body>
@if (Session["AuthState"] != "Authenticated")
{
Response.Redirect("~/login");
}
// other html
</body>
我一直在我的應用程序管理面板中使用此方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.