在ASP.net MVC自定义表单认证/授权方案 [英] Custom form authentication / Authorization scheme in ASP.net MVC

查看:155
本文介绍了在ASP.net MVC自定义表单认证/授权方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个使用窗体身份验证在ASP.NET MVC中一个自定义验证方案。我可能将要管理的网站上不同区域的想法 - 审批是和普通用户区,而这些将使用不同的登录页面,等等。所以,这就是我希望发生的。


  1. 用户访问受限制的网页(现在我有一个客户AuthorizeAttribute保护)

  2. 用户被重定向到一个特定的登录页面(而不是一个来自Web.config文件)。

  3. 用户凭证验证(通过自定义DATABSE方案),并在用户登录

真的AP preciate任何与此帮助!

这是我我有什么,到目前为止,这是行不通的:

 公共类AdministratorAccountController:控制器
{
    公众的ActionResult登录()
    {
        返回视图(登录);
    }    [HttpPost]
    公众的ActionResult登录(AdministratorAccountModels.LoginModel型号,串RETURNURL)
    {
        如果(ModelState.IsValid)
            如果(model.UserName ==管理员&放大器;&安培; model.Password ==通行证)//这将是从数据库等拉
            {
                VAR票=新的FormsAuthenticationTicket(1,//版本
                                                           model.UserName,//用户名
                                                           DateTime.Now,//创建时间
                                                           DateTime.Now.AddSeconds(30),//到期时间
                                                           假的,//持续
                                                           ); // 用户数据                VAR strEncryptedTicket = FormsAuthentication.Encrypt(票);
                VAR饼干=新的HttpCookie(FormsAuthentication.FormsCookieName,strEncryptedTicket);
                Response.Cookies.Add(饼干);                如果(!String.IsNullOrEmpty(RETURNURL))
                {
                    返回重定向(RETURNURL);
                }
                其他
                {
                    返回RedirectToAction(指数,家);
                }
            }
            其他
            {
                ModelState.AddModelError(,提供的用户名或密码不正确。);
            }        //如果我们走到这一步,事情失败了,重新显示形式
        返回查看(模型);
    }    [AdministratorAuthorize]
    公众的ActionResult的MainMenu()
    {
        返回查看();
    }    公共类AdministratorAuthorizeAttribute:AuthorizeAttribute
    {
        保护覆盖布尔AuthorizeCore(HttpContextBase的HttpContext)
        {
            VAR authenCookie = httpContext.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            如果(authenCookie == NULL)返回false;            VAR票= FormsAuthentication.Decrypt(authenCookie.Value);
            VAR ID =新FormsIdentity(票);
            VAR astrRoles = ticket.UserData.Split(新[] {','});
            VAR本金=新的GenericPrincipal(ID,astrRoles);
            HttpContext.User中=本金;
            返回true;
        }        保护覆盖无效HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            VAR模型=新AdministratorAccountModels.LoginModel();
            VAR可视数据=新的ViewDataDictionary(模型);            filterContext.Result =新的ViewResult {VIEWNAME =登录,ViewData的可视数据=};        }
    }
}


解决方案

我使用minus4建议code的组合和我自己的code以上创建这个简化的情况下,可能会帮助别人

。我加了一些评论有关的事情,我感到困惑在第一。

 公共类AdministratorAccountController:控制器
{
    公众的ActionResult登录()
    {
        返回视图(登录);
    }    [HttpPost]
    公众的ActionResult登录(AdministratorAccountModels.LoginModel型号,串RETURNURL)
    {
        如果(ModelState.IsValid)
            //在这里,您将调用一个服务来处理身份验证
            如果(model.UserName ==管理员&放大器;&安培; model.Password ==通行证)
            {
                // *! *
                //创建一个FromsAuthenticationTicket的是什么
                //将设置RequestContext.HttpContext.Request.IsAuthenticated为True
                //在AdminAuthorize属性code以下
                // *! *
                VAR票=新的FormsAuthenticationTicket(1,//版本
                                                           model.UserName,//用户名
                                                           DateTime.Now,//创建时间
                                                           DateTime.Now.AddSeconds(30),//到期时间
                                                           假的,//持续
                                                           ); //用户数据,例如角色                VAR strEncryptedTicket = FormsAuthentication.Encrypt(票);
                VAR饼干=新的HttpCookie(FormsAuthentication.FormsCookieName,strEncryptedTicket);
                Response.Cookies.Add(饼干);                //重定向回您试图访问的页面
                如果(!String.IsNullOrEmpty(RETURNURL))
                {
                    返回重定向(RETURNURL);
                }
                其他
                {
                    返回RedirectToAction(指数,家);
                }
            }
            其他
            {
                ModelState.AddModelError(,提供的用户名或密码不正确。);
            }        //如果我们走到这一步,事情失败了,重新显示形式
        返回查看(模型);
    }    [AdminAuthorize]
    公众的ActionResult的MainMenu()
    {
        返回查看();
    }    公共类AdminAuthorize:ActionFilterAttribute
    {
        公共覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
        {
            如果(!filterContext.RequestContext.HttpContext.Request.IsAuthenticated)
            {
                //重定向到所需的登录页面
                //这可以从配置文件或其他任何被拉
                filterContext.HttpContext.Response.Redirect(/ AdministratorAccount /登录?RETURNURL =
                                        + HttpUtility.UrlEn code(filterContext.HttpContext.Request.RawUrl));
            }            base.OnActionExecuting(filterContext);
        }
    }
}

I am trying to create a custom authentication scheme in ASP.NET MVC using form authentication. The idea that I might have different areas on the site that will be managed - approver are and general user area, and these will use different login pages, and so forth. So this is what I want to happen.

  1. User access restricted page (right now I have it protected with a customer AuthorizeAttribute)
  2. User is redirected to a specific login page (not the one from Web.config).
  3. User credentials are verified (via custom databse scheme) and user logs in.

Would really appreciate any help with this!!!

This is what I what I have so far, and it doesn't work:

 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 };

        }
    }
}

解决方案

I used a combination of code suggested by minus4 and my own code above to create this simplified scenario that might help someone else. I added some comments about things that confused me at first.

 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 MVC自定义表单认证/授权方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆