Redirect to previous page after login

I created an admin website using Asp.Net web forms.
When I share the URL of the page (not the home page) of my website with my friend, and when he enters it into his browser, he automatically redirects it to the login page. (This is the correct behavior). When he enters his username and password, he is redirected to the main page, not the URL that I shared with him.

I tried using Request.UrlReferrer.PathAndQuery in login.aspx.
It only works if the user intentionally logged out.

Basically, I want to share a link (url) by mail or something, the user will open it, he will ask for a login, if he has not logged in yet, after entering the browser he will show him a page with a URL and not on the home page.

+4
source share
3 answers

If you use Form Authentication , you can use querystring ReturnUrl on your login page:

 var returnUrl = Request.QueryString["ReturnURL"]; if (string.IsNullOrEmpty(returnUrl)){ returnUrl = "~/"; } Response.Redirect(returnUrl); 

If you do not use it, you should behave like it: When you redirect the user to the login page, add a request with the referrer page.

 //**Remember to url encode it!** var returnUrl = Server.UrlEncode(Request.Url.PathAndQuery); Response.Redirect("~/login.aspx?ReturnURL=" + returnUrl); 
+9
source

On each page, check if the user is registered, if not, then

 if (Session["UserName"] == null && Session["UserId"] == null) { string OriginalUrl = HttpContext.Current.Request.RawUrl; string LoginPageUrl = "/login"; HttpContext.Current.Response.Redirect(String.Format("{0}?ReturnUrl={1}", LoginPageUrl, OriginalUrl)); } 

and on the login page check if returnurl exists if returnurl exists redirecting to this page.

 if (this.Request.QueryString["ReturnUrl"] != null) { this.Response.Redirect(Request.QueryString["ReturnUrl"].ToString()); } else { this.Response.Redirect("/account/default"); } 
+7
source

Alternatively, you can use cookies. I prefer this method because it leads to a cleaner address bar and looks more elegant. Also, the process is transparent to the user. This should also prevent some cybercriminals from using your login page to redirect to unwanted websites.

In the code where you are redirected to the login page:

 Response.Cookies.Add(new HttpCookie("returnUrl", Request.Url.PathAndQuery)); Response.Redirect("login.aspx"); 

On the login page:

 HttpCookie returnCookie = Request.Cookies["returnUrl"]; if((returnCookie == null) || string.IsNullOrEmpty(returnCookie.Value)) { Response.Redirect("Default.aspx"); } else { HttpCookie deleteCookie = new HttpCookie("returnUrl"); deleteCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(deleteCookie); Response.Redirect(returnCookie.Value); } 

it

Note. If you encounter security problems, you should do some checking on the returned URL.

+2
source

Source: https://habr.com/ru/post/1491444/


All Articles