我想在ASP.NET MVC中使用窗体身份验证创建一个自定义身份验证方案。我可能会在网站上有不同的区域,即将被管理的想法 - 审批者和一般用户区域,这些区域将使用不同的登录页面,等等。所以这就是我想要发生的事情。ASP.net中的自定义窗体身份验证/授权方案MVC
- 用户访问受限制的网页(现在我已经将其与客户AuthorizeAttribute保护)
- 用户被重定向到一个特定的登录页面(而不是一个从Web.config文件)。
- 用户凭据进行验证(通过自定义DATABSE方案)和用户登录。
会很感激的任何帮助!
这是我我有什么,到目前为止,这是行不通的:
public class AdministratorAccountController : Controller
{
public ActionResult Login()
{
return View("Login");
}
[HttpPost]
public ActionResult Login(AdministratorAccountModels.LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
if (model.UserName == "admin" && model.Password == "pass") // This will be pulled from DB etc
{
var ticket = new FormsAuthenticationTicket(1, // version
model.UserName, // user name
DateTime.Now, // create time
DateTime.Now.AddSeconds(30), // expire time
false, // persistent
""); // user data
var strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
Response.Cookies.Add(cookie);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
[AdministratorAuthorize]
public ActionResult MainMenu()
{
return View();
}
public class AdministratorAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authenCookie = httpContext.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (authenCookie == null) return false;
var ticket = FormsAuthentication.Decrypt(authenCookie.Value);
var id = new FormsIdentity(ticket);
var astrRoles = ticket.UserData.Split(new[] { ',' });
var principal = new GenericPrincipal(id, astrRoles);
httpContext.User = principal;
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var model = new AdministratorAccountModels.LoginModel();
var viewData = new ViewDataDictionary(model);
filterContext.Result = new ViewResult { ViewName = "Login", ViewData = viewData };
}
}
}
形式认证代码是伟大的。但有一点要注意,我认为最好的做法是只在本地重定向到url。这减轻了重定向攻击的可能性。请参阅:http://www.asp.net/mvc/tutorials/security/preventing-open-redirection-attacks – 2012-11-02 21:27:57