Asp.Net MVC 自定义登录过滤器

1、新建类BaseController用于统一所有控制器继承扩展,方便扩展登录等过滤器。示例如下:

using CloudWave.JustBeHere.JBH_H5.Controllers.Attribute;
using CloudWave.JustBeHere.JBH_H5.Controllers.Authorization;
using CloudWave.JustBeHere.JBH_H5.Models.User;
using CloudWave.JustBeHere.Web;
using Jil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using static CloudWave.JustBeHere.JBH_H5.Models.Commn.BaseModel;

namespace CloudWave.JustBeHere.JBH_H5.Controllers
{
    [Auth]
    [ResultFilter]
#if (!DEBUG)
    [Error]
#endif
    public class BaseController : Controller
    {

        public Authentication authentication = Authentication.Instance;
        public bool IsLogin
        {
            get
            {
                //return true;
                return authentication.IsLogin;
            }
        }
        public LoginResult Operator
        {
            get
            {
                return authentication.CurrentUser;
            }
        }
        private string _hostName;

        /// 
        /// 获取请求的域名
        /// 
        public string HostName
        {
            get
            {
                if (string.IsNullOrEmpty(_hostName))
                {
                    var url = Request.Url.ToString();
                    // http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]?
                    var reg = new Regex(@"//([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]+/?");
                    var result = reg.Match(url, 0).Value;
                    _hostName = result;
                }
                return _hostName;
            }
        }

        private string _hostFullName;

        /// 
        /// 获取请求的域名全称(含请求协议)
        /// 
        public string HostFullName
        {
            get
            {
                if (string.IsNullOrEmpty(_hostFullName))
                {
                    var url = Request.Url.ToString();
                    // http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]?
                    var reg = new Regex(@"http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]+/?");
                    var result = reg.Match(url, 0).Value;
                    _hostFullName = result;
                }
                return _hostFullName;
            }
        }

        /// 
        /// 是否为手机端访问
        /// 
        public bool IsMobile
        {
            get
            {
                var uAgent = Request.ServerVariables["HTTP_USER_AGENT"];
                var b = new Regex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                return b.IsMatch(uAgent) || v.IsMatch(uAgent.Substring(0, 4));
            }
        }
    }
}
View Code

2、新建类Authentication用于管理SessionCookie等信息。示例如下:

using CloudWave.JustBeHere.JBH_H5.Models.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace CloudWave.JustBeHere.JBH_H5.Controllers.Authorization
{
    public class Authentication
    {
        public const string UserSessionKey = "UserInfo";

        private Authentication()
        {
        }

        public static Authentication Instance
        {
            get
            {
                return new Authentication();
            }
        }

        /// 
        /// 写入验证信息
        /// 
        /// 
        /// 是否保存
        public void SetAuth(LoginResult uInfo, bool isPersistent)
        {
            string token = uInfo.Id + "|" + uInfo.Token;
            //将用户ID和角色写入Cookie
            FormsAuthentication.SetAuthCookie(token, isPersistent, FormsAuthentication.FormsCookiePath);
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(token, isPersistent);
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
            //FormsAuthentication.RedirectFromLoginPage(ticket.Name, true);

            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, DateTime.Now.AddDays(30), ticket.IsPersistent, "");
            authCookie.Value = FormsAuthentication.Encrypt(newTicket);
            HttpContext.Current.Response.AddHeader("P3P", "CP=CAO PSA OUR");//解决ie js跨域调用
            HttpContext.Current.Response.Cookies.Add(authCookie);
            SetSession(uInfo);
        }

        /// 
        ///保存用户状态
        /// 
        /// 
        public void SetSession(LoginResult uInfo)
        {
            HttpContext.Current.Session[UserSessionKey] = uInfo;
        }
        /// 
        ///保存用户状态
        /// 
        /// 
        public void SetSession(int uid)
        {
            bool setFlag = false;
            if (HttpContext.Current.Session == null)
            {
                throw new ArgumentNullException("SessionState Failed");
            }
            if (HttpContext.Current.Session[UserSessionKey] == null)
            {
                setFlag = true;
            }
            else
            {
                //得到用户信息
                LoginResult sulr = HttpContext.Current.Session[UserSessionKey] as LoginResult;
                if (sulr.Id != uid) setFlag = true;
            }
            if (setFlag)
            {
                try
                {
                    //var u = GetUserInfo();
                    //if (u != null)
                    //{
                    //    HttpContext.Current.Session[UserSessionKey] = u;
                    //}
                    new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "Index", controller = "Home" }));
                }
                catch { }
            }
        }
        private LoginResult GetUserInfo()
        {
            var client = new Api(WebCommon.ApiUrl, WebCommon.ActiveUser, WebCommon.ApiToken);
            LoginResult slr = new LoginResult();
            client.Request.Header.Cmd = "api/staffuser/getstaffuserinfo";
            slr = client.ExecutePost();
            if (client.Response.Header.statusCode == 1000)
            {
                return slr;
            }
            else { return null; }
        }

        /// 
        /// 登出
        /// 
        public void SignOut()
        {
            FormsAuthentication.SignOut();
            HttpContext.Current.Session.Clear();
        }

        public bool IsLogin
        {
            get
            {
                return HttpContext.Current != null ? HttpContext.Current.Request.IsAuthenticated : false;
            }
        }

        /// 
        /// 当前用户信息
        /// 
        public LoginResult CurrentUser
        {
            get
            {
                if (!IsLogin)
                {
                    return null;
                }
                int uid;
                if (int.TryParse(HttpContext.Current.User.Identity.Name.Split('|')[0], out uid))
                {
                    if (HttpContext.Current.Session[UserSessionKey] == null)
                    {
                        SetSession(uid);
                    }
                    return HttpContext.Current.Session[UserSessionKey] as LoginResult;
                }
                return null;
            }
        }

        //public void RefreshInfo()
        //{
        //    UsersExtensionInfo u = UsersService.GetById(HttpContext.Current.User.Identity.Name);
        //    u.ImName = UsersService.GetImName(u.TTUserId);
        //    HttpContext.Current.Session[UserSessionKey] = UserInfoDec(u);
        //}
    }
}
View Code

 3、新建类AuthAttribute,继承AuthorizeAttribute类。示例如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CloudWave.JustBeHere.JBH_H5.Controllers.Attribute
{
    /// 
    /// 登录过滤器
    /// 
    public class AuthAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var controller = filterContext.Controller as BaseController;
            if (controller.IsLogin)
            {
                filterContext.Controller.ViewBag.UserInfo = controller.Operator?.Id;
                // filterContext.Controller.ViewBag.PartnerName = controller.Operator?.PartnerName;
            }
            else
            {
                filterContext.Controller.ViewBag.UserInfo = "";
              //  filterContext.Controller.ViewBag.PartnerName = "";
            }
            if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                if (!controller.IsLogin)
                {
                    //if (filterContext.HttpContext.Request.IsAjaxRequest())
                    //{
                    //    filterContext.Result = new JsonResult
                    //    {
                    //        Data = "needlogin",
                    //        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    //    };
                    //}
                    //else
                    //{
                    //    string reutrnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;
                    //    filterContext.Result = new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "index", controller = "Home", returnUrl = reutrnUrl }));

                    //}
                    string reutrnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;
                    filterContext.Result = new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "index", controller = "Home", returnUrl = reutrnUrl }));
                }
            }
            //if (!AuthorizeCore(filterContext.HttpContext)) {
            //    HandleUnauthorizedRequest(filterContext);
            //} else {
            //    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //}
        }
    }
}
View Code

 4、在Web.config的节点system.web下新增如下节点配置:

<authentication mode="Forms">
      <forms loginUrl="/Home/Index" timeout="43200">forms>
authentication>

5、返回信息过滤器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace CloudWave.JustBeHere.JBH_H5.Controllers.Attribute
{

    /// 
    /// 请求返回结果过滤器
    /// 
    public class ResultFilterAttribute : ActionFilterAttribute
    {

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (filterContext.Result is ViewResult)
            {
                var controller = (BaseController)filterContext.Controller;
                FormsAuthentication.SignOut();
                HttpContext.Current.Session.Clear();
            }
            base.OnResultExecuting(filterContext);
        }
    }
}
View Code

 

转载于:https://www.cnblogs.com/miskis/p/8716263.html

你可能感兴趣的:(Asp.Net MVC 自定义登录过滤器)