38

I want to remove "returnurl=/blabla" from address bar when a user want to access to a login required page. Because I'm trying to redirect the user to a static page after login to do some selections.

How can I do that?

RPM1984
  • 69,608
  • 55
  • 212
  • 331
Ali Ersöz
  • 14,982
  • 10
  • 47
  • 62

10 Answers10

22

This is the nature of Forms Authentication. (which im guessing you're using).

That is, when you access a page which requires authentication, ASP.NET will redirect you to the login page, passing in the ReturnUrl as a parameter so you can be returned to the page you came from post-login.

To remove this functionality would break the semantics and design of Forms Authentication itself. (IMO)

My suggestion - if you dont need it, dont use it.

I'm trying to redirect the user to a static page after login to do some selections.

Piece of cake - after you've done your login, instead of doing FormsAuthentication.RedirectFromLoginPage (which uses that very ReturnUrl QueryString parameter), just use FormsAuthentication.SetAuthCookie and redirect wherever you want.

RPM1984
  • 69,608
  • 55
  • 212
  • 331
  • FormsAuthentication.SetAuthCookie is what I'm doing right now.I just want to remove it from address bar. – Ali Ersöz Sep 15 '10 at 19:57
  • Then my first comment stands - you may as well not use Forms Authentication at all. There is no easy way to do this (that i know of). Remebering ANY page can redirect to the login page (and ASP.NET does this). Only way i can think of is to hook into a Global.asax event and rewrite the URL. Why do you care if the URL is there? – RPM1984 Sep 15 '10 at 21:58
  • and that comment contradicts your comment "Because I'm trying to redirect the user to a static page after login to do some selections.". The ReturnURL will not prevent you from doing your own redirect after login, UNLESS you're using RedirectFromLoginPage, which you have said you arent. So i dont know what youre issue is. How is the ReturnUrl preventing you from doing a redirect? – RPM1984 Sep 15 '10 at 21:59
  • 1
    I guess this is preventing nothing. It's just that, as this information is not used, it would be nice to not have it. – Julien N Apr 18 '11 at 13:46
  • 7
    The data in the RedirectUrl part of the query string can potentially be used in an enumeration attack, depending on what it shows. There are legitimate reasons to hide that data from the user. – TheSmurf Jan 24 '13 at 20:37
  • @DannySmurf - no it can't. The RedirectUrl has exactly that - a URL and nothing more, no login information whatsoever. – RPM1984 Jan 24 '13 at 22:45
  • That's incorrect. It's not a URL and nothing more; whatever is in the query string is also relayed. Depending what the application has dumped in there, there is of course a possibility that there's information that could be exploited. That's a particular danger in a multi-user environment. It's also a danger for larger/corporate applications, parts of which are less cautious about redirects that happen before authentication. Any application information is a potential vector for an enumeration attack, not just login information... There are legitimate reasons to hide this data from the user. – TheSmurf Jan 29 '13 at 17:34
  • Okay, take your point. I was under the assumption that the "previous" page did not have any sensitive information in the URL/querystring. – RPM1984 Jan 30 '13 at 23:29
  • Not useful, because it doesn't answer the question on how to remove it. What if you are hitting the urls only? – Demodave Feb 28 '20 at 21:12
14

Add this to your Global.asax file.

public class MvcApplication : HttpApplication {

  private const String ReturnUrlRegexPattern = @"\?ReturnUrl=.*$";

  public MvcApplication() {

    PreSendRequestHeaders += MvcApplicationOnPreSendRequestHeaders;

  }

  private void MvcApplicationOnPreSendRequestHeaders( object sender, EventArgs e ) {

    String redirectUrl = Response.RedirectLocation;

    if ( String.IsNullOrEmpty(redirectUrl) 
         || !Regex.IsMatch( redirectUrl, ReturnUrlRegexPattern ) ) {

      return;

    }

    Response.RedirectLocation = Regex.Replace( redirectUrl, 
                                               ReturnUrlRegexPattern, 
                                               String.Empty );

  }
William Humphreys
  • 1,102
  • 1
  • 11
  • 31
  • http://stackoverflow.com/questions/13394999/form-authentication-and-url-rewriting I'm using Custom forms Authentication. If I use the code which you have given the control loops over and over and it says - `Too many Redirects`. I think the problem is, when the Control goes to `Login` Page like `mywebsite.com/Login`, then It checks for authentication and It redirects to `Login.aspx` page. and your code redirects again to `Login` page . This loop continues. Can you help me with this ??? – Krishna Thota Nov 15 '12 at 11:15
  • Don't we need a `:base()` in MvcApplication constructor? – Roberto Apr 14 '16 at 22:19
  • How do you add it to the Global.asax? Where does it go - incomplete answer. – Demodave Feb 28 '20 at 21:13
  • 1
    You simple add the Properties / Methods to the MvcApplication class. There is nothing else to add really. Though for note this is a nearly 10 year old question. With the changing nature of the .Net environment it may not even be relevant or accurate anymore. – William Humphreys Mar 02 '20 at 15:09
11

Create a custom Authorize Attribute

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(
                        AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            string loginUrl = "/"; // Default Login Url 
            filterContext.Result = new RedirectResult(loginUrl);
        }
    }
}

then use it on your controller

[CustomAuthorizeAttribute]
public ActionResult Login()
{


    return View();
}
Aivan Monceller
  • 4,281
  • 9
  • 36
  • 69
  • 2
    I prefer this solution, although I believe it makes more sense to have the code in `HandleUnauthorizedRequest` and use this line instead `filterContext.Result = new RedirectResult( FormsAuthentication.LoginUrl );` – Pierluc SS Jul 04 '13 at 19:09
9

Simple...

[AllowAnonymous]
public ActionResult Login() { return View(); }

[AllowAnonymous]
public ActionResult LoginRedirect(){ return RedirectToAction("Login"); }

Webconfig

<authentication mode="Forms">
    <forms loginUrl="~/Account/LoginRedirect" timeout="2880" />
</authentication>
  • In my case I had to change the path in startup.auth.cs and not in web config: `app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString(("/Account/LoginRedirect")), ...` I also used RedirectToActionPermanent instead of RedirectToAction because it's pernament. – Ronen Festinger Dec 29 '14 at 00:42
  • This is a good solution - the only caveat is that you would have the request to LoginRedirect in your browser history, so if someone hits the Back button once, it would bring them back to LoginRedirect and then right back to Login. – Jim Dec 01 '15 at 20:15
8

As RPM1984 pointed out, you don't have to redirect the user to the specified URL after signing in.

If it is imperative that you remove the ReturnUrl querystring parameter there are a couple options. Probably the easiest is in your login web page / controller you'd check for the existence of a ReturnUrl parameter in the Request.QueryStrings collection. If it exists, you could do a redirect back to the login page, but without the ReturnUrl.

Another option would be to create a custom implementation for the FormsAuthenticationModule, which is the class that handles authenticating a user based on their form authentication ticket and is responsible for redirecting unauthorized users to the login page. Unfortunately, the FormsAuthenticationModule class's methods are not virtual, so you can't create a derived class and override the methods needed, but the good news is that the class is pretty simple - just maybe 100-200 lines of code in total, and using Reflector you could quickly create your own custom FormsAuthenticationModule class. If you go this route (which I wouldn't recommend), all that you'd need to do would be to take out the code in the OnLeave method that tacks on the ReturnUrl parameter. (In addition to modifying this class you'd also need to configure your Web.config file so that your application uses your custom FormsAuthenticationModule class rather than the one in the .NET Framework.)

Happy Programming!

Scott Mitchell
  • 8,343
  • 3
  • 47
  • 70
3

Add a location tag to your web.config. If your page is in a subdirectory, add the web.config to the subdirectory.

<location path="ForgotPassword.aspx">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>

ASP will overlook adding the ReturnUrl querystring and directing to login.

Spooky
  • 2,848
  • 8
  • 24
  • 39
Fio
  • 41
  • 2
  • wow, I had this issue look here http://stackoverflow.com/questions/19301787/asp-net-links-wont-redirect-to-the-right-page Thanks it helped me, and we had the same page name :) – meda Oct 10 '13 at 17:59
2

if you are using asp.net control loginstatus then click on login status control press f4( for properties) under behavior section we can see LogOutAction there select Return to Login page.

Note: In order to implement it successfully you must have a login page with name login.aspx

Malachi
  • 3,182
  • 4
  • 27
  • 45
Rohith
  • 37
  • 5
2

If you want to remove returnURL from request and redirect to specific path, you can follow this steps.

Firstly get the current context, verify if the user is authenticated and finally redirect the current path.

  HttpContext context = HttpContext.Current;
        //verify if the user is not authenticated
        if (!context.User.Identity.IsAuthenticated)
        {
            //verify if the URL contains  ReturnUrl   
            if (context.Request.Url.ToString().Contains("ReturnUrl"))
            {
                //redirect the current path
                HttpContext.Current.Response.Redirect("~/login.aspx");
            }

        }

I put this code into Page_Load method from my class Login.aspx.cs

1

You can use the HttpUtility.ParseQueryString to remove that element. If you use VB.NET then this code does this

Dim nvcQuery As NameValueCollection
Dim strQuery As String = ""

If Not IsNothing(Request.QueryString("ReturnUrl")) Then
    If Request.QueryString("ReturnUrl").Length Then
        nvcQuery = HttpUtility.ParseQueryString(Request.QueryString.ToString)
        For Each strKey As String In nvcQuery.AllKeys
            If strKey <> "ReturnUrl" Then
                If strQuery.Length Then strQuery += "&"
                strQuery += strKey + "=" + nvcQuery(strKey)
            End If
        Next
        If strQuery.Length Then strQuery = "?" + strQuery
        If Request.CurrentExecutionFilePath <> "/default.aspx" Then
            Response.Redirect(Request.CurrentExecutionFilePath + strQuery)
        Else
            Response.Redirect("/" + strQuery)
        End If
        Response.Write(Server.HtmlEncode(strQuery))
    End If
End If

I would put this in the Page.Init event - obviously you will need to change the "/default.aspx" to match the URL of your login page.

Adam
  • 11
  • 1
0
void Application_BeginRequest(object s, EventArgs e)
{
    // ................

    // strip return Return Url
    if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])  && Request.Path.IndexOf("login.aspx")!=-1)
        System.Web.HttpContext.Current.Response.Redirect("~/login.aspx");
Otto
  • 46
  • 3