Authorize的Forms认证

Posted 彪悍的代码不需要注释

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Authorize的Forms认证相关的知识,希望对你有一定的参考价值。

页面请求步骤:

1.登录地址: http://localhost:4441/SysLogin/AdminLogin

2.登陆成功地址:http://localhost:4441/Frame/MainFrame 

3.点击页面退出,清除Session/Cookie跳转到登录页面

4.Url输入登录成功的地址界面自动验证授权进入:http://localhost:4441/SysLogin/AdminLogin?ReturnUrl=%2fFrame%2fMainFrame

代码实现步骤:

1.登录页面:SysLogin/AdminLogin,不继承BaseController

[HttpPost]
        [OperateLoggerFilter(IsRecordLog = false, ConName = "系统登录", ActName = "用户登录")]
        public ActionResult LoginAuthentica(string Account, string Pwd)
        {
            try
            {
                var Result = AdminServiceDb.GetEntityByWhere(it => it.Account == Account);
                if (Result == null)
                {
                    return Json(new { result = false, msg = "用户不存在" });
                }
                else
                {
                    Pwd = StringHelper.MD5(Pwd);
                    if (Result.PassWord != Pwd)
                    {
                        return Json(new { result = false, msg = "密码错误" });
                    }
                    DateTime overdueDate;
                    string value = Result.ID.ToString();
                    value = Encrypt.Encrypto(value);
                    overdueDate = DateTime.Now.AddMinutes(30);
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                1,
                                Guid.NewGuid().ToString(),
                                DateTime.Now,
                                overdueDate,
                                false,
                                value
                                );
                    FormsAuthenticationTicket t = new FormsAuthenticationTicket(0, "", DateTime.Now, overdueDate, false, value);
                    string hashTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
                    Response.Cookies.Add(cookie);
                    string url = Url.Action("MainFrame", "Frame");
                    return Json(new { result = true, msg = url });
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(this, ex);
                return Json(new { result = false, msg = "异常:登录失败" });
            }
        }
登录方法

2.登录成功后:Frame/MainFrame,继承BaseController

  [System.Web.Mvc.Authorize]//引用授权
    
    public class FrameController : BaseController
    {
        ......

3.WebConfig配置:

    <authentication mode="Forms">
      <forms loginUrl="~/SysLogin/AdminLogin" timeout="2880" />
    </authentication>

4.登录Controller的特性页面:

 public class OperateLoggerFilter : FilterAttribute, IActionFilter
    {


        private LogService logServiceDb = new LogService();

        /// <summary>
        /// 是否记录日志,默认为不记录
        /// </summary>
        public bool IsRecordLog = false;


        /// <summary>
        /// 控制器中文名
        /// </summary>
        public string ConName = string.Empty;

        /// <summary>
        /// 方法中文名
        /// </summary>
        public string ActName = string.Empty;

        /// <summary>
        /// 是否为form提交,若是则设置为true,否则报错,默认为false
        /// </summary>
        public bool IsFormPost = false;

        /// <summary>
        /// 如果是form提交(IsFormPost为true),则需要设置此字段,此字段代表请求方法的参数类型集合
        /// </summary>
        public Type[] Entitys = null;

        /// <summary>
        /// Action执行后
        /// </summary>
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {

            if (!IsRecordLog)
                return;

            //var result = string.Empty;
            if (filterContext.Result is ViewResult)
                return;
            //result = ((System.Web.Mvc.JsonResult)filterContext.Result).Data.ToString();

            string controller = filterContext.Controller.ToString();

            string action = filterContext.ActionDescriptor.ActionName;

            Type type = Type.GetType(controller);
            ParameterInfo[] parasInfo = null;
            if (!IsFormPost)
                parasInfo = type.GetMethod(action).GetParameters();
            else
                parasInfo = type.GetMethod(action, Entitys).GetParameters();

            if (parasInfo == null || parasInfo.Length == 0)
                return;

            StringBuilder content = new StringBuilder();
            if (!IsFormPost)
                foreach (var item in parasInfo)
                {
                    content.Append(item.Name);
                    content.Append(":");
                    if (filterContext.HttpContext.Request[item.Name] == null)
                        content.Append("null");
                    else
                        content.Append(filterContext.HttpContext.Request[item.Name].ToString());
                    content.Append(";");
                }
            else
                foreach (var item in parasInfo)
                {
                    PropertyInfo[] fileds = Entitys[0].GetProperties();
                    foreach (var f in fileds)
                    {
                        if (filterContext.HttpContext.Request[f.Name] == null)
                            continue;
                        content.Append(f.Name);
                        content.Append(":");
                        content.Append(filterContext.HttpContext.Request[f.Name].ToString());
                        content.Append(";");
                    }

                }

            var user = filterContext.HttpContext.User.Identity.Name;

            //-------------
            string cookieName = FormsAuthentication.FormsCookieName;//从验证票据获取Cookie的名字。
            //取得Cookie.
            HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
            if (null == authCookie)
                return;
            FormsAuthenticationTicket authTicket = null;
            //获取验证票据。
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            if (authTicket == null)
                return;

            //验证票据的UserData中存放的是用户信息。
            //UserData本来存放用户自定义信息。
            string userData = authTicket.UserData;
            string userId = Foc_Sys_Public.Encrypt.Decrypto(userData);
            FormsIdentity id = new FormsIdentity(authTicket);
            //把生成的验证票信息和角色信息赋给当前用户.

            Guid uid;
            if (Guid.TryParse(userId, out uid))
            {
                var model = new LogEntity
                {
                    ID = Guid.NewGuid(),
                    UserID = uid,
                    Controller = ConName.Trim() == string.Empty ? controller : ConName.Trim(),
                    Action = ActName.Trim() == string.Empty ? action : ActName.Trim(),
                    Content = content.ToString().Length > 500 ? content.ToString().Substring(0, 500) : content.ToString(),
                    //OperateResult = result.Contains("True") ? true : false,
                    IsDel = false,
                    CreatTime = DateTime.Now,
                };

                logServiceDb.AddEntity(model);
            }
        }

        /// <summary>
        /// Action执行前
        /// </summary>
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {

        }
    }

 5.BaseController页面:

  /// <summary>
    ///  基础控制器 所有控制器必须继承
    /// </summary>
    [System.Web.Mvc.Authorize]
    public class BaseController : Controller
    {

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string IsAjax = Request.Headers["X-Requested-With"];
            if (string.IsNullOrEmpty(IsAjax))
            {
                if (!IsCheckJJurisdicti(filterContext))
                {
                    filterContext.Result = Redirect(Url.Action("Page503", "Frame"));
                }
            }
            base.OnActionExecuting(filterContext);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.ExceptionHandled = true;
                LogHelper.Error(filterContext.Controller, filterContext.Exception);
            }
            filterContext.Result = Redirect(Url.Action("Page503", "Frame"));
            base.OnException(filterContext);
        }
}
BaseController页面

 注意:

<system.webServer>
<!--<modules>
<remove name="FormsAuthentication" />
</modules>-->
</system.webServer>  配置文件要注释掉这句。不然进入会404错误。

以上是关于Authorize的Forms认证的主要内容,如果未能解决你的问题,请参考以下文章

权限管理之ASP.NET Forms身份认证

asp.net mvc如何实现多个登录页自动跳转的身份认证?

在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

细说ASP.NET Forms身份认证

细说ASP.NET Forms身份认证

Auth0 /authorize 端点不返回 JWT