0

I have a requirement to switch on/off some of the features for my application. I am using WebApi and for each feature we have separate controller/class created which contains the WebApi calls for that particular feature.

When any WebApi call comes to controller I want to check the flag in the DB and base on that flag I want to allow/deny the WebApi call. Any suggestions?

Admin can on/off feature anytime (after the deployment also). Below is my sample code.

 [RoutePrefix("api/Customer")]
 [Authorize(Roles = "ABC")]
 public class MyController : ApiController
{
[HttpPut]
    [Route("{xyz}/abcd")]
    [Authorize(Roles = "ABC")]
    public async Task<IModel> CreateCust(string username)
    {
}

[HttpPut]
    [Route("{test}/test")]
    [Authorize(Roles = "ABC")]
    public async Task<IModel> UpdateCust(string username)
    {
}
}

Thanks,

Pratik

Pratik Mehta
  • 1,310
  • 4
  • 15
  • 37

2 Answers2

1

You need to create your own class and inherit from System.Web.Http.AuthorizeAttribute.

Then you need to override OnAuthorization and add in your extra logic there.

public class CustomAuth : System.Web.Http.AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);


            // Check if for your database value in here
        }
    }

Then instead of [Authorize(Roles = "ABC")] you do [CustomAuth(Roles = "ABC")]

Andres Castro
  • 1,848
  • 16
  • 16
1

You can create custom action filter, and fill Response if action is restricted in order to prevent action execution. Use System.Web.Http.Filters.ActionFilterAttribute:

public class RestrictionCheckAttribute : ActionFilterAttribute 
{
    public override void OnActionExecuting(HttpActionContext actionContext) 
    {
        if (IsActionRestricted(actionContext))
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
        }
        base.OnActionExecuting(actionContext);
    }

    private bool IsActionRestricted(HttpActionContext actionContext)
    {
        // Add your restriction check logic here.
    }
}

Then decorate actions that need to be checked with that attribute. Of if you need to execute that logic before all actions you can register global action filter through HttpConfiguration.

Community
  • 1
  • 1
Leonid Vasilev
  • 11,910
  • 4
  • 36
  • 50