What initially sets the ReturnUrl parameter when using AuthorizeAttribute

前端 未结 2 477
北海茫月
北海茫月 2020-12-05 19:28

In an ASP.NET MVC project, when you decorate a class or method with [Authorize] and authorization fails, the site automatically redirects to the login page (using the loginU

相关标签:
2条回答
  • 2020-12-05 19:58

    The returnUrl querystring parameter is added to the redirect to the login page inside the FormsAuthentication class in the System.Web.dll assembly. FormsAuthenticion.RedirectToLoginPage method overloads end up calling the internal method, GetLoginPage. Both the name of the "ReturnUrl" variable and the LoginUrl can be overridden via web.config settings.

    When the default AuthorizeAttribute encounters an unauthorized request, it just returns an HttpUnauthorizedResult, which is just a wrapper around the HttpStatusCodeResult with a status code of 401. The FormsAuthenticationModule kicks in behind the scenes and does the rest of the work. There is no direct interaction between MVC and these base classes, unless of course you are calling the FormsAuthentication class static methods directly.

    Your solution is a standard one, when you want to override this behavior.

    The GetLoginPage method that does the work is as follows:

    internal static string GetLoginPage(string extraQueryString, bool reuseReturnUrl)
    {
        HttpContext current = HttpContext.Current;
        string loginUrl = FormsAuthentication.LoginUrl;
        if (loginUrl.IndexOf('?') >= 0)
        {
            loginUrl = FormsAuthentication.RemoveQueryStringVariableFromUrl(loginUrl, FormsAuthentication.ReturnUrlVar);
        }
        int num = loginUrl.IndexOf('?');
        if (num >= 0)
        {
            if (num < loginUrl.Length - 1)
            {
                loginUrl = string.Concat(loginUrl, "&");
            }
        }
        else
        {
            loginUrl = string.Concat(loginUrl, "?");
        }
        string str = null;
        if (reuseReturnUrl)
        {
            str = HttpUtility.UrlEncode(FormsAuthentication.GetReturnUrl(false), current.Request.QueryStringEncoding);
        }
        if (str == null)
        {
            str = HttpUtility.UrlEncode(current.Request.RawUrl, current.Request.ContentEncoding);
        }
        loginUrl = string.Concat(loginUrl, FormsAuthentication.ReturnUrlVar, "=", str);
        if (!string.IsNullOrEmpty(extraQueryString))
        {
            loginUrl = string.Concat(loginUrl, "&", extraQueryString);
        }
        return loginUrl;
    }
    
    0 讨论(0)
  • 2020-12-05 20:24

    try this

     returnUrl = filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped) ;
    

    i found it here Generate a return Url with a custom AuthorizeAttribute

    This works for me.

    0 讨论(0)
提交回复
热议问题