【问题标题】:Where should I place a check that may redirect a request?我应该在哪里放置可能重定向请求的检查?
【发布时间】:2010-10-24 15:15:42
【问题描述】:

如果用户的密码已过期,我需要将用户重定向到更改密码页面。

我想将此代码放在一个地方,以便任何请求都可以重定向到更改密码页面。

我已经研究过扩展 AuthorizeAttribute 并覆盖 OnActionExecuting,但两者都不起作用/允许我短路路由逻辑以重定向到密码更改页面。

为了澄清一点,逻辑是:

未经授权的请求:
-> 任何 URL -> AuthorizeAttribute -> Login.aspx -> 密码过期 -> ChangePassword.aspx

授权请求:
-> 任何 URL -> ????????? -> ChangePassword.aspx

是吗???我不知道该怎么做的部分。


我想我将继续扩展 AuthorizeAttribute。我将在所有除了密码更改控制器方法中使用它。

【问题讨论】:

    标签: asp.net-mvc authorization redirect routes


    【解决方案1】:
    public class DenyExpiredPasswordAttribute : AuthorizeAttribute
    {
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            IPrincipal user = filterContext.HttpContext.User;
    
            if(user != null)
            {
                if (user.Identity.IsAuthenticated)
                {
    
                    if (CurrentUser.PasswordExpired) // your checking of password expiration
                    {
                        filterContext.HttpContext.Response.Redirect("~/Account/ChangePassword?reason=expired");
                    }
                }
            }
            base.OnAuthorization(filterContext);
        }
    }
    

    这很好用,只需使用此属性标记每个控制器,不包括“帐户”一个。这样,在更改密码之前,具有过期属性的用户都无法继续。

    【讨论】:

    • 这基本上是我的选择。
    • 我知道这是一个旧答案,所以我想我会补充一点(至少对于 MVC3)filterContext.HttpContext.Response.Redirect("~/Account/ChangePassword?reason=expired"); 应该替换为filterContext.Result = new RedirectResult("~/Account/ChangePassword?reason=expired");(基于:stackoverflow.com/a/2187364/700926stackoverflow.com/a/2765148/700926 )
    【解决方案2】:

    您可以考虑在 global.asax 中为 PostAuthenticateRequest 事件添加事件处理程序。

    protected void Application_Start(object sender, EventArgs e) {
      this.PostAuthenticateRequest += new EventHandler(Global_PostAuthenticateRequest);
    }
    
    void Global_PostAuthenticateRequest(object sender, EventArgs e)
    {
     if (passwordExpired) {
       Context.Response.Redirect("~/ChangePassword.aspx");
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多