0

I have a Controller which implements an AuthorizableApi Class.

[AttributeUsage(AttributeTargets.Method)]
public class AuthorizableRoute : Attribute { }

public class AuthorizableApi : ApiController
{
    public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
    {
        /* Add functionality here to secure the API */
        return base.ExecuteAsync(controllerContext, cancellationToken);
    }
}

This allows me to secure an entire controller, however I also want to be able secure a single action. Using the controllerContext I can get the controller and route but I don't know if it's possible to get an attribute on that action.

    [HttpPost]
    [AuthorizableRoute]
    public HttpResponseMessage DataAction([FromBody] DataType data)
    {
        /* Actions */
    }

So, I'd like to be able to do something like...

if(Attribute.GetCustomAttribute(myRoute, typeof (AuthorizableRoute)) != null) { }

If this isn't possible then what could be a viable alternative?

1 Answer 1

1

You could do this by implementing a Filter. You should however inherit the AuthorizationFilterAttribute and implement the OnAuthorization(HttpActionContext context) method. It should be something like this:

public class AuthorizableRouteFilterAttribute : AuthorizationFilterAttribute
{
   public override void OnAuthorization(HttpActionContext context)
   {  
      IPrincipal principal = Thread.CurrentPrincipal;            
      /*Your authorization check here*/

      if (!principal.IsInRole("YourRole")) // or whatever check you make
      {
           context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
           return;
      }
   }        
}


[HttpPost]
[AuthorizableRouteFilter]
public HttpResponseMessage DataAction([FromBody] DataType data)
{
    /* Actions */
}
Sign up to request clarification or add additional context in comments.

1 Comment

I discovered and ended up using AuthorizeAttribute, but after some quick research it looks like AuthorizationFilterAttribute is the better way to go. Thanks!

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.