【问题标题】:Overriding AuthorizeAttribute in MVC 4在 MVC 4 中覆盖 AuthorizeAttribute
【发布时间】:2013-10-14 11:05:24
【问题描述】:

在我的应用程序中,我想重定向授权用户以更新他们的个人资料页面,直到他们提供了所需的信息。如果他们更新配置文件,则 IsProfileCompleted 在数据库中设置为“true”。

所以,我知道这可以通过将检查条件置于控制器所需的操作中来完成。 但我想通过自定义AuthorizeAttribute 来做到这一点。

我在 Google 上搜索并“StackOverflowed”以获取信息,但感到困惑。请指导我。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


    【解决方案1】:
    public class MyAuthorizeAttribute: AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);
            if (!authorized)
            {
                // The user is not authorized => no need to go any further
                return false;
            }
    
            // We have an authenticated user, let's get his username
            string authenticatedUser = httpContext.User.Identity.Name;
    
            // and check if he has completed his profile
            if (!this.IsProfileCompleted(authenticatedUser))
            {
                // we store some key into the current HttpContext so that 
                // the HandleUnauthorizedRequest method would know whether it
                // should redirect to the Login or CompleteProfile page
                httpContext.Items["redirectToCompleteProfile"] = true;
                return false;
            }
    
            return true;
        }
    
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile"))
            {
                var routeValues = new RouteValueDictionary(new
                {
                    controller = "someController",
                    action = "someAction",
                });
                filterContext.Result = new RedirectToRouteResult(routeValues);
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    
        private bool IsProfileCompleted(string user)
        {
            // You know what to do here => go hit your database to verify if the
            // current user has already completed his profile by checking
            // the corresponding field
            throw new NotImplementedException();
        }
    }
    

    然后你可以用这个自定义属性来装饰你的控制器动作:

    [MyAuthorize]
    public ActionResult FooBar()
    {
        ...
    }
    

    【讨论】:

    • 我正在使用此示例在我的 mvc 应用程序中进行自定义授权。但是,它不会将其重定向到返回 url。我错过了什么吗?
    • 我又来了,上面的问题已经解决了。我正在使用基于会话的登录,有时它会执行应在授权后执行的代码。我正在使用会话密钥的静态属性。你能帮我解决这个问题吗? protected override bool AuthorizeCore(HttpContextBase httpContext) { if (string.IsNullOrEmpty(CurrentUser.UserName) || CurrentUser.UserName == " ") return false;返回真; }
    • 这个答案是否与 MVC 5 兼容,还是我们应该进行任何更改?
    【解决方案2】:

    我采用了这段代码并添加了一些我自己的更改,即检查当前登录的用户是否在服务器上具有会话状态,它们不像以前那样昂贵!

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);
            if (!authorized && !Membership.isAuthenticated())
            {
                // The user is not authorized => no need to go any further
                return false;
            }
    
            return true;
        }
    }
    public class Membership
    {
        public static SystemUserDTO GetCurrentUser()
        {
            // create a system user instance
            SystemUserDTO user = null;
    
            try
            {
                user = (SystemUserDTO)HttpContext.Current.Session["CurrentUser"];
            }
            catch (Exception ex)
            {
                // stores message into an event log
                Utilities.Log(ex.Message, System.Diagnostics.EventLogEntryType.Warning);
    
            }
            return user;
        }
    
        public static bool isAuthenticated()
        {
            bool loggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
            bool hasSession = (GetCurrentUser() != null);
            return (loggedIn && hasSession);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 2021-05-27
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 2011-10-01
      • 2014-07-04
      相关资源
      最近更新 更多