ASP.NET Core 5: Best way to use common URL for login page and root page

744 Views Asked by At

In an ASP.NET Core 5 web app with Identity (and in earlier versions), the URL for the login page defaults to:

https://[yourhost]/account/login

and once you're logged in, the root of your project lives at:

https://[yourhost]

But in many (most?) web apps, the login page shares the URL with the root page. Using Facebook as an exmaple, before I'm logged in, the URL is https://www.facebook.com, and after logging in the URL is the same. What's the best way to achieve this in ASP.NET Core?

The best solution I have so far is:

(AccountController.cs)

        [HttpGet]
        [AllowAnonymous]
        [Route("/")]
        public async Task<IActionResult> Login(string returnUrl = null)
        {
            // If authenticated, serve the application page.
            if (User.Identity.IsAuthenticated)
            {
                return View("~/Views/Weather/Index.cshtml");
            }
            // Otherwise, serve the login page.
            else
            {
                ViewData["ReturnUrl"] = returnUrl;
                return View();
            }
        }

This doesn't feel great because , from AccountController, I'm returning a view that should correspond to WeatherController.

Ideally, I'd like to say, "for URL '/' , only if the user is logged in, match this endpoint in the weather controller. Else, fall back to this other endpoint in the account controller." I was thinking this might be possible with a custom route constraint, but I'm not necessarily passing any parameters to the URL. I was also looking into DynamicRouteValueTransformer, but wasn't successful.

Or, is it misguided for me to try to have the login page share a URL with the root page? Thanks for any suggestions.

1

There are 1 best solutions below

1
Armin Shoeibi On

Change Default Settings of Identity Framework,

  services.ConfigureApplicationCookie(options =>
    {
        // Cookie settings
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

        options.LoginPath = "/Home/Index/; // here
        options.AccessDeniedPath = "/Identity/Account/AccessDenied";
        options.SlidingExpiration = true;
    });

after that check, if the user is authenticated return a different view, and if the user is not authenticated return a different view that user can login.