Working with return url in asp.net core

43,501

Solution 1

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");

Solution 2

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!

Solution 3

you can use Events to get the Request and redirect to what url you want like this sample.

services.ConfigureApplicationCookie(options => {

            options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
            {
                OnRedirectToLogin = ctx =>
                {
                    var requestPath = ctx.Request.Path;
                    if (requestPath.Value == "/Home/About")
                    {
                        ctx.Response.Redirect("/Home/UserLogin");
                    }
                    else if (requestPath.Value == "/Home/Contact")
                    {
                        ctx.Response.Redirect("/Home/AdminLogin");
                    }

                    return Task.CompletedTask;
                }
            };

        });

see this link: How to redirect access denied login based on the URL on ASP.NET Core 2 Identity?

Share:
43,501
XamDev
Author by

XamDev

Senior Software Engineer

Updated on July 09, 2022

Comments

  • XamDev
    XamDev almost 2 years

    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
    
  • XamDev
    XamDev over 6 years
    Yes, I am specifically setting the LoginPath in authentication option as I am not able to add the client name in login path OR not able to dynamically build the login path. So that is my question how should do that ?