來實現在ASP.NET MVC項目的認證和授權的最簡單的方法之一是使用inbuild窗體身份驗證模塊。當您創建一個新的ASP.NET MVC項目時,它已經包含了開始使用Forms Auth所需的全部內容。
它所要做的就是創建某些表(5),並且您永遠不必擔心或在代碼中跟蹤它們。它非常簡單。您始終可以將由ASP.NET MVC成員資格提供者創建的用戶映射到您自己的UserMaster
表。
接下來,您所要做的就是標記您的ActionMethod或Controller,或者在global.asax屬性中設置[Authorize]
屬性,然後全部設置。
代碼將是簡單:
進行登錄:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password,
persistCookie: model.RememberMe))
{
///rest of the logic
}
}
也低於是這會派上用場一些的Userful功能:
if(WebSecurity.UserExists(username)){ /// ur logic }
//or
WebSecurity.CreateUserAndAccount(username, password);
//or
System.Web.Security.Roles.AddUserToRole(username, UserRole);
你猜怎麼着,你不不必擔心在某些HttpModule
中設置某個標誌,或者首先執行函數以查看會話User是否存在,[Authorize]
屬性ta凱斯關心這一點。
映射定製UserMaster
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password,
persistCookie: model.RememberMe))
{
try
{
try
{
//below is my custom method IsValidUser with my own logic for
// valid user
MembershipCore.IsValidUser(model.UserName);
if (MembershipCore.isFirstTimeLogin(model.UserName))
{
//Show License Screen in a window
return RedirectToAction("License");
}
//my custom method setting custom Session variables
MembershipCore.SetLoggedInUser(model.UserName);
}
}
}
自定義的成員提供的想法是使用現有的會員提供與自己的數據方案。您可以將會員/角色存儲在Cookie中並從中檢索。我會建議不要使用會話變量。 – lopezbertoni