tags:

views:

47

answers:

1

I'm implementing a class for all my controllers to inherit that will redirect to login page if user is not authenticated. The RedirectToAction line is not redirecting though. Can you plesae help correct?

public class SecureController : Controller
    {
        public SecureController()
        {
            if (User == null || !User.Identity.IsAuthenticated)
            {
                RedirectToAction("Logon", "Account");
            }
        }
    }
+1  A: 

My suggestion would be to use an ActionFilter instead. It will be much easier. You can do something like this:

public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // You can do any custom authentication logic in here

        if (User == null || !User.Identity.IsAuthenticated)
        {
            // This assumes that Account is the controller, and Logon is the action method.
            // You might want to check your routes if this is still not working correctly
            RedirectToAction("Logon", "Account");
        }
    }
}

This will let you then just put an attribute on your action method in your controller like so:

[RequiresAuthentication]
public ActionResult Index()
{
    return View();
}

Or, as others have pointed out, if you do not need any custom authentication logic, you can just use the AuthorizeAttribute:

[Authorize]
public ActionResult Index()
{
    return View();
}
mc2thaH
That is already built in. See the Authorize attribute
TT
It also works better than this one, as it supports caching.
Craig Stuntz
I assumed he was needing to do custom authentication since he was going the direction he was. This is the type of attribute I use, I just substituted out all of my custom authentication logic.
mc2thaH
Great advice about the filter. I am implementing my own authorization logic and the filter will come in handy. Thanks.
Cyril Gupta