I'm developing an application using MVC 5. I have written code for login functionality. When I tried to launch application, Login page is getting added with a query string parameter ReturnUrl. Here is my code:
public ActionResult Login()
{
var authentication = Authentication;
if (Request.HttpMethod == "POST")
{
//code for user validation
}
return View();
}
I'm unable to find the code that is adding ReturnUrl parameter to url. Can anyone help me, where I can find code that adds ReturUrl parameter?
By default, AuthorizeAttribute class is part of System.Web.Mvc namespace (see Github repository: aspnetwebstack). The method leads to login redirection there is HandleUnauthorizedRequest:
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.
filterContext.Result = new HttpUnauthorizedResult();
}
HTTP 401 status code response from method above will trigger FormsAuthenticationModule (see reference below), where OnLeave method redirects to login URL with FormsAuthentication.ReturnUrlVar property included:
strRedirect = loginUrl + "?" + FormsAuthentication.ReturnUrlVar + "=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding);
// Do the redirect
context.Response.Redirect(strRedirect, false);
To override this behavior (including remove ReturnUrl part), create an authorization class extends from AuthorizeAttribute class, e.g. (this is an example implementation):
using System.Web.Mvc;
using System.Web.Routing;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
// @Override
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new { controller = "Account",
action = "Login"
}));
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
Then, you may implement custom authorization attribute like this one:
[CustomAuthorizeAttribute]
public ActionResult UserPage()
{
return View();
}
NB: Use AuthorizeAttribute on all pages that requires user login authentication, for login page use AllowAnonymousAttribute instead.
Related references:
System.Web.Security.FormsAuthenticationModule (MS Github reference)
What initially sets the ReturnUrl parameter when using AuthorizeAttribute
Generate a return Url with a custom AuthorizeAttribute
How to remove returnurl from url?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With