1

I have a project with Identity 3.0. I have setup a dynamic menu which also works and displays a different menu list depending on what role you are in.

I would like Authorized users to have different home page. If you are UnAuthorized you should see "/Home/Index" as per normal.

If you are Authorized (logged in as a user and it remembers you..) you should always be directed to a different home page for Authorized users... say "/Scheduling/Index".

I have set an AuthorizeFilter

           services.AddMvc(setup =>
        {
            setup.Filters.Add(new AuthorizeFilter(defaultPolicy));
        });

so unless you are Authorized you get sent to the login page if you are try an access any controller without the:

[AllowAnonymous]

at the start... eg HomeController has this at the start...

I found this on Stackoverflow and tried it in the StartUp class but it doesnt work.

            services.Configure<CookieAuthenticationOptions>(options =>
        {
            options.LoginPath = new PathString("/Scheduler/Index");
        });

How can I have two different home pages depending on whether the user is logged in or not logged in?

Community
  • 1
  • 1
si2030
  • 2,799
  • 4
  • 25
  • 60

1 Answers1

3

You have (at least) two ways:

1) Return different view names from your 'Index' action (depending on user status):

[AllowAnonymous]
public IActionResult Index()
{
     // code for both (anonymous and authorized) users
     ...

     var shouldShowOtherHomePage = ... // check anything you want, even specific roles
     return View(shouldShowOtherHomePage ? "AuthorizedIndex" ? "Index", myModel);
}

This one is good when your Index method have no "heavy" logic, different for anonymous/authorized users, and you will not have two "branches" of code inside one method.

2) Redirect authorized users to other action from Index:

[AllowAnonymous]
public IActionResult Index()
{
    var shouldShowOtherHomePage = ...
    if (shouldShowOtherHomePage) 
    {
        return RedirectToAction("AuthorizedIndex", "OtherController");
    }

    // code for anonymous users
    ....
}

Use this option when you don't want to mix two logic flows inside one method, or your actions are in different controllers.

Dmitry
  • 13,497
  • 3
  • 52
  • 68
  • Hi @Dimitry and others.. is there a way to do this just from the StartUp.cs class using filters etc. I would rather have it in the Startup if possible – si2030 May 24 '16 at 06:47
  • You can use [Action filters](https://docs.asp.net/en/latest/mvc/controllers/filters.html#action-filters) with action/controller-specific logic or [create own Middleware](https://docs.asp.net/en/latest/fundamentals/middleware.html#writing-middleware) if you have url-specific logic (for example redirect user to other URL based on current URL and some other conditions) and place in before Mvc middleware. Both are configured in `Startup.cs` – Dmitry May 24 '16 at 08:04