gpt4 book ai didi

asp.net - ASP.net MVC中的自定义表单例份验证/授权方案

转载 作者:行者123 更新时间:2023-12-04 05:10:42 25 4
gpt4 key购买 nike

我正在尝试使用表单例份验证在ASP.NET MVC中创建自定义身份验证方案。我可能会在站点上拥有将要管理的不同区域的想法-批准人区域和一般用户区域,这些区域将使用不同的登录页面,依此类推。所以这就是我要发生的事情。

  • 用户访问限制页面(现在我已使用客户的AuthorizeAttribute保护它)
  • 用户被重定向到特定的登录页面(而不是Web.config的登录页面)。
  • (通过自定义数据库方案)验证用户凭据并登录用户。

  • 非常感谢您的帮助!!!

    这是我到目前为止所拥有的,并且不起作用:
     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 };

    }
    }
    }

    最佳答案

    我结合使用minus4建议的代码和上面的我自己的代码来创建此简化的场景,该场景可能会对其他人有所帮助。一开始,我添加了一些让我感到困惑的事情的评论。

     public class AdministratorAccountController : Controller
    {
    public ActionResult Login()
    {
    return View("Login");
    }

    [HttpPost]
    public ActionResult Login(AdministratorAccountModels.LoginModel model, string returnUrl)
    {
    if (ModelState.IsValid)
    // Here you would call a service to process your authentication
    if (model.UserName == "admin" && model.Password == "pass")
    {
    // * !!! *
    // Creating a FromsAuthenticationTicket is what
    // will set RequestContext.HttpContext.Request.IsAuthenticated to True
    // in the AdminAuthorize attribute code below
    // * !!! *
    var ticket = new FormsAuthenticationTicket(1, // version
    model.UserName, // user name
    DateTime.Now, // create time
    DateTime.Now.AddSeconds(30), // expire time
    false, // persistent
    ""); // user data, such as roles

    var strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
    Response.Cookies.Add(cookie);

    // Redirect back to the page you were trying to access
    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);
    }

    [AdminAuthorize]
    public ActionResult MainMenu()
    {
    return View();
    }

    public class AdminAuthorize : ActionFilterAttribute
    {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
    if (!filterContext.RequestContext.HttpContext.Request.IsAuthenticated)
    {
    // Redirect to the needed login page
    // This can be pulled from config file or anything else
    filterContext.HttpContext.Response.Redirect("/AdministratorAccount/Login?ReturnUrl="
    + HttpUtility.UrlEncode(filterContext.HttpContext.Request.RawUrl));
    }

    base.OnActionExecuting(filterContext);
    }
    }
    }

    关于asp.net - ASP.net MVC中的自定义表单例份验证/授权方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2329197/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com