I have a Controller
call GlobalController
, all Controllers
will inherit from it, and its objective is to validate if the user is already authenticated, then, declaring the constructor GlobalController
of this way:
public class GlobalController : Controller
{
IAuthenticationManager Authentication
{
get { return HttpContext.GetOwinContext().Authentication; }
}
public GlobalController()
{
if (!Authentication.User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Login");
}
}
}
Is it possible that if a user is not authenticated, I am redirected to LoginController
?
As it is, my code sends me the following error message:
Error 2 Since 'Web.Project.Controllers.GlobalController.GlobalController()' returns void, a return keyword must not be followed by an object expression
Which is logical because a return value is not expected, if I remove the return
so that the instruction remains this way, it RedirectToAction("Index", "Login");
is as if it did not perform any action, it does not generate an error and the execution of the code continues.
Note: I use MVC 5 and Owin Authentication
The solution is to create a
FilterAttribute
, in this way it can be validated if the user is authenticated on the site, and if they are not logged in, it will redirect to Login:Code of
FilterAttribute
:Code of
Controller
:Thus, all those
Controllers
who inherit from willGlobalController
go through itValidateAuthenticationFilterAttribute
to validate the session.Try using this:
The attribute
Authorize
verifies if you authenticated to the site, if you didn't it redirects you to the Login page.