我正在尝试使用表单身份验证在ASP.NET MVC中创建自定义身份验证方案。我的想法是我可能会有不同的站点区域需要管理,如审核员区域和普通用户区域,它们将使用不同的登录页面等。所以这就是我想要发生的事情。
以下是我希望实现的步骤:
1. 用户访问受限页面(目前我已经使用自定义AuthorizeAttribute进行保护)。 2. 用户被重定向到特定的登录页面(而不是Web.config中的页面)。 3. 验证用户凭据(通过自定义数据库方案)并登录。
非常感谢您的帮助!
这是我目前的代码,但它无法正常工作:
以下是我希望实现的步骤:
1. 用户访问受限页面(目前我已经使用自定义AuthorizeAttribute进行保护)。 2. 用户被重定向到特定的登录页面(而不是Web.config中的页面)。 3. 验证用户凭据(通过自定义数据库方案)并登录。
非常感谢您的帮助!
这是我目前的代码,但它无法正常工作:
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 };
}
}
}