2

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");
    }
}

2 Answers 2

2

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" }));
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

This is going to sound pretty dim but is there a specific place within the solution that this would need to be placed? Thanks
There is no such requirement. You can pick any location that matches your project structure but be aware that this attribute should know about your "StaffId".
Thanks, makes sense. I'll have a go!
I've tried implementing this and used [Authorize] on the relevant controller but it still allows access. The value of StaffId is definitely 0. Any suggestions please?
You should your attribute not Authorize. Like [StaffOnly] which is inherited from Authorize attribute.
0

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.

1 Comment

Unfortunately there's 30k+ users and the check will need to be performed each time any action is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.