Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with return url in asp.net core

We are trying to redirect the user(using return URL) to the login page if the user is not authenticated/authorized while accessing the particular URL. However, we are not able to add the custom parameters(clientname in this case) in route while redirecting the user to the login page. We are using asp.net identity core framework.

In Startup.cs we have defined the below route which will be applicable to all.

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Edge",
                    template: "{clientname}/{controller}/{action}");
            });

also added below the line of code to ensure that all URLs required authentication

services.AddMvc(o =>
{
   o.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
})

and configured the IdentityOptions for redirecting to the login page as follows

services.Configure<IdentityOptions>(opt =>
{
  opt.Cookies.ApplicationCookie.LoginPath = new PathString("/Account/Login");
});

and in Account Controller below is the login method

[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
    this.ViewData["ReturnUrl"] = returnUrl;
    return View();
}

If the user tries to access any URL without authentication it should redirect to login page. Consider below Index method from Home Controller as an example.

public IActionResult Index()
{
    return View();
}

But whenever we try to redirect the user to login page it does not append the client name in the URL. It forms below the URL where clientname is missing in /Account/Login

http://localhost:5002/Account/Login?ReturnUrl=/ClientA/home/index

Because of this, it is resulting in 404 Page not found error.So what changes we need to do for proper redirection.

The Url should be formed as follows

http://localhost:5002/ClientA/Account/Login?ReturnUrl=/ClientA/home/index
like image 696
XamDev Avatar asked Aug 22 '17 05:08

XamDev


People also ask

How does return URL work?

When an unauthenticated user tries to get into a section of your application which requires authentication, then returnUrl comes into the picture. The Url requested by the unauthenticated user is basically stored in returnurl .

What is return URL in asp net?

You can use this method when you want to perform the redirect in your application code instead of using the RedirectFromLoginPage method. The GetRedirectUrl method returns the URL specified in the query string using the ReturnURL variable name.

How do I remove returnUrl from URL?

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. Show activity on this post. If you want to remove returnURL from request and redirect to specific path, you can follow this steps.


2 Answers

It seems they changed it in .Net Core MVC

How it worked for me:

public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = "")
{
    ....... other codes

    if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
       return Redirect(returnUrl);
    else
       return RedirectToAction("Index", "Home");
}

Now move to HTML Razor Code:

@{
    ViewData["Title"] = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var returnUrl = @Context.Request.Query["returnurl"];
}

<form asp-action="Login" asp-route-returnurl="@returnUrl">
   <!--Rest of your login page HTML -->
</form>

And it works smoothly now!

like image 152
Ali Adravi Avatar answered Sep 27 '22 20:09

Ali Adravi


You're specifically setting the LoginPath on your authentication options. By default, it will always direct you there when you are unauthenticated, regardless of the resource you tried to reach. I believe you may have to replace or inherit/override some of the innards in order to have the LoginPath be dynamic based off of the resource you request. I'm not sure if dynamic LoginPaths are natively supported otherwise? I could be wrong.

On an unrelated security note, you should verify that the resource in the ReturnUrl is local to your application before attempting to use it, or even return the homepage of your app. Otherwise it's possible for a malformed URL to spoof the redirect location to an resource designed to mimic the real one in appearance, but with malicious intent.

if (Url.IsLocalUrl(returnUrl))
    return Redirect(returnUrl);
else
    return RedirectToAction("Index", "Home");
like image 34
Nick Albrecht Avatar answered Sep 27 '22 19:09

Nick Albrecht