JinYazhou +

MVC中实现简单的身份认证和授权

前言

因为系统不是很复杂,不需要很细的粒度,只需要控制相应角色只能打开相应页面就可以了。MVC自带的身份验证不是很轻巧,而且只能用SQL SERVER。所以,重写下Form认证是最好的方法。

单用户

首先,先配置web.config

  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Login" timeout="2880" />
    </authentication>
  </system.web>


新建UserAuthAttribute.cs

    public class UserAuthAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string session = httpContext.Session["Root"] == null ? string.Empty : httpContext.Session["Root"].ToString();
            if (session != "LoginTrue")
                return false;
            else
                return true;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.HttpContext.Response.StatusCode == 403)
            {
                filterContext.Result = new RedirectResult("/Home/Index");
            }
        }
    }

使用方法:action上添加[UserAuth]

多用户

新建RoleCheckAttribute.cs

    public class RoleCheckAttribute : ActionFilterAttribute
    {
        public string Roles { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!string.IsNullOrEmpty(Roles))
            {
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    if (filterContext.HttpContext.Request.Url != null)
                    {
                        string returnUrl = filterContext.HttpContext.Request.Url.AbsolutePath;
                        string redirectUrl = string.Format("?ReturnUrl={0}", returnUrl);
                        string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                        filterContext.HttpContext.Response.Redirect(loginUrl, true);
                    }
                }
                else
                {
                    string[] strRoles = Roles.Split(',');
                    bool isAuthenticated = JudgeAuthorize(filterContext.HttpContext.User.Identity.Name, strRoles);

                    filterContext.HttpContext.Response.Write("Model Role:" + Roles + ",Name:" + filterContext.HttpContext.User.Identity.Name + ",GetRole:" + GetRole.GetRoleByName(filterContext.HttpContext.User.Identity.Name) + ",isAccess:" + isAuthenticated.ToString());

                    if (!isAuthenticated)
                    {
                        throw new UnauthorizedAccessException("You have no right to view the page!");
                    }
                }
            }
            else
            {
                throw new InvalidOperationException("No Role Specified!");
            }
        }

        private static bool JudgeAuthorize(string userName, string[] strRoles)
        {
            string userAuth = GetRole.GetRoleByName(userName);
            return strRoles.Contains(userAuth, StringComparer.OrdinalIgnoreCase);
        }

        private static string GetRole(string name)
        {
            switch (name)
            {
                case "aaa": return "User";
                case "bbb": return "Admin";
                case "ccc": return "Manager";
                default: return "Fool";
            }
        }
    }
用法:action上添加[RoleCheck(Roles = "User,Admin")]

也可以把Controller和action对应的Roles写到xml,在App_Start/FilterConfig.cs里全局注册一下。

最新评论