Home > Blockchain >  Which is the simplest way to redirect to page when user is not logged in in ASP.NET MVC?
Which is the simplest way to redirect to page when user is not logged in in ASP.NET MVC?

Time:02-06

I have two simple login and home controllers:

public class LoginController : Controller
{
        public LoginController()
        {
            
        }

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

public class HomeController : Controller
    {
        public HomeController()
        {
            
        }

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

    }

I would like to redirect to login/index every time when user is not logged in. How can I achieve that? Thank you very much.

CodePudding user response:

You can use Authorize attribute which as part of Forms authentication in ASP.NET-MVC. To do that you need to setup forms authentication first in your web.config:

Under the <system.web> element, place:

<authentication mode="Forms">
  <forms loginUrl="~/Login/Index" timeout="45" slidingExpiration="true" cookieless="UseCookies" protection="All" requireSSL="false" enableCrossAppRedirects="false" defaultUrl="~/Home/Index" path="/" />
</authentication>

Now in your LoginController, when you are authenticating a user, it will be something like this:

public class LoginController : Controller
{
        public LoginController()
        {
            
        }

        public IActionResult Index()
        {               
            return View();
        }
        
        [HttpPost]
        [AllowAnonymous]
        public IActionResult ValidateUser()
        {
          //your user authentication logic here
          if(userAuthenticated)
          {
             FormsAuthentication.SetAuthCookie(userModel, false);
          }
  
           return View("Index");
        }
}

Once you have authenticated your user, then you can place the Authorize attribute either on class action or method depending on your need:

Require authorized user only to access entire class and its methods:

[Authorize]
public class HomeController : Controller
{
    public HomeController()
    {
        
    }

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

}

Require user to only be authorized for Index method:

public class HomeController : Controller
{
    public HomeController()
    {
        
    }

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

}
  •  Tags:  
  • Related