asp.net mvc 使用AuthorizeAttribute做授权验证

授权验证,比如登陆验证

1、自定义属性继承AuthorizeAttribute

2、重写OnAuthorization方法

3、通过AllowAnonymousAttribute特性处理无需授权的Action或者Controller

实现代码:

public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        CookieService MyCookie = new CookieService();

        private long _UserCode = 0;

        /// <summary>
        /// 获取用户编码
        /// </summary>
        public long UserCode
        {
            get
            {
                object userCode = UrlDeCode(MyCookie.Get("UserCode"));
                if (userCode != null)
                {
                    long code = 0;

                    long.TryParse(userCode.ToString(), out code);

                    _UserCode = code;
                }
                else
                {
                    _UserCode = 0;
                }
                return _UserCode;
            }
        }

        /// <summary>
        /// 验证授权
        /// 1、添加AllowAnonymous特性的,跳过所有授权,包括登陆授权
        /// 2、检验登陆授权
        /// 3、检验功能授权
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // 跳过登陆授权
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }

            // 是否ajax请求
            bool isAjax = filterContext.HttpContext.Request.IsAjaxRequest();

            // 开始跳转
            try
            {
                // 用户编码为0时,重新登陆
                if (UserCode == 0)
                {
                    filterContext.Result = RedirectLogin();

                    return;
                }

                // 跳过权限
                if (filterContext.ActionDescriptor.IsDefined(typeof(NoAuthorizeAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoAuthorizeAttribute), true))
                {
                    return;
                }

                // 这里开始判断权限
                string controller = filterContext.RouteData.Values["controller"].ToString();
                string action = filterContext.RouteData.Values["action"].ToString();
                string area = string.Empty;

                if (filterContext.RouteData.DataTokens.ContainsKey("area"))
                {
                    area = filterContext.RouteData.DataTokens["area"].ToString();
                }

                bool isPermission = true;

                // 无权限时,跳转
                if (!isPermission)
                {
                    // 跳转
                    filterContext.Result = RedirectNoPermission(isAjax);

                    return;
                }
            }
            catch (Exception ex)
            {
                Logging.Logger.Error(ex);

                filterContext.Result = RedirectLogin();
            }
        }

        /// <summary>
        /// 跳转到无权限的提示
        /// </summary>
        /// <param name="isAjax"></param>
        /// <returns></returns>
        public RedirectToRouteResult RedirectNoPermission(bool isAjax)
        {
            RouteValueDictionary routeValue = null;

            if (isAjax)
            {
                routeValue = new RouteValueDictionary(new { action = "AjaxNoPermission", controller = "Permission" });
            }
            else
            {
                routeValue = new RouteValueDictionary(new { action = "NoPermission", controller = "Permission" });
            }

            return new RedirectToRouteResult(routeValue);
        }

        /// <summary>
        /// 跳转到登录页
        /// </summary>
        /// <returns></returns>
        public RedirectToRouteResult RedirectLogin()
        {
            var routeValue = new RouteValueDictionary(
                                new
                                {
                                    action = "Index",
                                    controller = "login",
                                    area = "Fire",
                                    //ReturnUrl = url
                                });

            return new RedirectToRouteResult(routeValue);
        }

        /// <summary>
        /// 解码
        /// </summary>
        public string UrlDeCode(string str)
        {
            return System.Web.HttpUtility.UrlDecode(str, System.Text.Encoding.UTF8);
        }
    }

  

使用代码:

[UrlAuthorize]
    public class HomeController : Controller
    {
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        //[UrlAuthorize]
        public ActionResult Test()
        {
            return View();
        }
    }

 

全局使用:

在App_Start/FilterConfig中添加

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
            //filters.Add(new HandleErrorAttribute());

            // 授权验证 取消注释时,会开启
            // filters.Add(new MyAuthorizeAttribute());
        }

  

posted @ 2020-02-25 16:03  我要找到我的全世界  阅读(745)  评论(0)    收藏  举报