1

I have my auth controller which on successful login redirects the user to my dashboard controller with the user.identity properties populated, so I can use User.IsAuthenticated and User.IsInRole("Admin")

My question is.

Once the user is logged in and are on the dashboard page. How can I redirect them back to the dashboard page if they're already logged in.

Thanks in advance.

cwiggo
  • 2,541
  • 9
  • 44
  • 87
  • On page load you can check if user is already authenticated. If yes then redirect to dashboard page immediately. If no then process login and then redirect. – Roman Apr 12 '19 at 13:11
  • @RomanDoskoch can you provide this as an answer? Some code would be cool. i think I've already got the solution but to get it as an answer would get you the votes++ and help the community if they come across this problem. Cheers. – cwiggo Apr 12 '19 at 13:13

2 Answers2

3

So my solution was to simply check if the user was already authenticated in my [HttpGet] login controller as opposed to my [HttpPost] login controller.

[HttpGet]
public ActionResult Login()
{
    if (User.Identity.IsAuthenticated)
        return RedirectToAction("Index", "Dashboard");

    return View();
}

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel req)
{

    return View(req);
}
cwiggo
  • 2,541
  • 9
  • 44
  • 87
0

Implement Authentication. And make Dashboard default controller. Magic will happen, out of the box.

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{

...

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
         .AddCookie("user_by_cookie", options =>
         {
             options.LoginPath = "/Login/Index/";
         })
...


}



public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
 app.UseAuthentication();

 app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Dashboard}/{action=Index}/{id?}");
 });
...
}

Login Controller

    [Authorize(AuthenticationSchemes = "user_by_cookie")]
public class LoginController : Controller
{

    [HttpGet]
    [AllowAnonymous]
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public IActionResult Index()
    {
        ...
        //authenticate();
        ...
        return View();
    }

    [HttpGet]
    public IActionResult Logout()
    {
        ..
        // logout();  -> 
        ..
        return RedirectToAction("Index");
    }

}

in Dashboard Controller

    [Authorize(AuthenticationSchemes = "user_by_cookie")]
public class DashboardController : Controller
{

    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }

}
Andrzej Reduta
  • 767
  • 1
  • 7
  • 15