Gareth
Gareth

Reputation: 5243

ASP.NET MVC Redirect All Request if Condition Met

I'm looking to implement a site wide redirect to my MVC5 app based on a condition.

I've researched the adding [Authorize] to my base controller but this will not be adequate as my site runs on Windows Authentication but I need to validate that the user is present in a separate, business owned hierarchy that does not connect with AD.

I've researched filters and understand that a custom action filter may be required here. Am I trying to implement this the correct way and where should this be within the project?

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(StaffId == 0)
    {
        filterContext.Result = RedirectToAction("Error");
    }
}

Upvotes: 2

Views: 1449

Answers (2)

TotalWar
TotalWar

Reputation: 355

If you have a low number of users, i would put all the Ids present in a separate, business owned hierarchy in a cache (that would refresh itself from the database at a certain interval) to save time so you do not hit the database on each and every request.

Alternative to this is to have a cookie present after they login that never expires that indicates that they also belong to that separate business owned hierarchy.Then you can read that cookie and perform the redirect.Encryption of that cookie might be necessary depending on your requirments.

Upvotes: 0

serhiyb
serhiyb

Reputation: 4833

Create custom Authorize attribute, like:

public class StaffOnlyAttribute : AuthorizeAttribute
{
  protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
      return StaffId != 0;
  }

  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
  {
      base.HandleUnauthorizedRequest(filterContext);
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "YourController", action = "Error" }));
  }
}

Upvotes: 2

Related Questions