ASP.net MVC中的自定义表单身份验证/授权方案
发布时间:2020-12-16 00:20:36  所属栏目:asp.Net  来源:网络整理 
            导读:我正在尝试使用表单身份验证在ASP.NET MVC中创建自定义身份验证方案.我可能在网站上有不同区域的想法 – 审批者是和一般用户区域,这些将使用不同的登录页面,等等.所以这就是我想要发生的事情. 用户访问受限页面(现在我用客户AuthorizeAttribute保护它) 用户
                
                
                
            | 
                         我正在尝试使用表单身份验证在ASP.NET MVC中创建自定义身份验证方案.我可能在网站上有不同区域的想法 – 审批者是和一般用户区域,这些将使用不同的登录页面,等等.所以这就是我想要发生的事情. 
  
  
>用户访问受限页面(现在我用客户AuthorizeAttribute保护它) 非常感谢任何帮助! 这就是我到目前为止所做的,它不起作用: 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 };
        }
    }
}
解决方法
 我使用了减号和上面我自己的代码建议的代码组合来创建这个可能对其他人有帮助的简化方案.我添加了一些关于最初让我困惑的事情的评论. 
  
  
  
        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,// 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",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 Core 与 EntityFramework Core 课程介绍
 - asp.net – 仅刷新另一个UpdatePanel中的UpdatePanel
 - asp.net-mvc – UserManager.AddPasswordAsync()返回“Name
 - asp.net-mvc – ‘System.Web.Webpages.Html.Htmlhelper’不
 - asp.net-mvc – AntiForgeryToken在ASP.Net MVC 4 RC中弃用
 - asp.net-mvc – 将MVC内容文件夹放入Area
 - asp.net – Web.config中的瑞典语文本
 - asp.net core 使用identityServer4的密码模式来进行身份认证
 - asp.net – 从两个表(join)获取数据,并使用linq返回结果
 - 如何在ASP.NET中删除/放弃请求?
 
推荐文章
            站长推荐
            - 当我尝试添加映射文件时,ASP.NET脚手架的问题
 - asp.net-mvc – 如何gzip内容在asp.net MVC?
 - asp.net-mvc-3 – 首先是ASP.Net MVC 3 EF4.1代码
 - asp.net-mvc – 上传文件:MemoryStream与文件系
 - 从经典ASP检测移动用户代理并在会话启动时重定向
 - asp.net – 如何在web.config中读取会话状态信息
 - .net-assembly – 如何将DNU WRAP用于不在ASP.Ne
 - asp.net-mvc – 是否有一个ASP.NET MVC HtmlHelp
 - asp.net – 在Windows 7笔记本电脑中找不到IIS_I
 - asp.net-mvc – 如何在.NET MVC3 HTML表单中的必
 
热点阅读
            