Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET WEB API Custom Authorize and Exception Handling Attributes

0.00/5 (No votes)
27 May 2012 1  
How to implement the custom authorization and exception handling attribute in the ASP.NET Web API.

Introduction

In this article, I will explain and demonstrate how to implement the custom authorization and exception handling attribute in the ASP.NET Web API.

Custom Authorize Attribute

in ASP.NET WEB API you can extend "AuthorizeAttribute" to implement custom authorization filter to control the access to the application. I have overridden the "OnAuthorization" method to check custom authorization rules. In this implementation, I am assuming that user will send and receive the data through "HTTP headers".

Following is code example how to implement it.

public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
{
    public override void OnAuthorization(
           System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        base.OnAuthorization(actionContext);
        if (actionContext.Request.Headers.GetValues("authenticationToken") != null)
        {
            // get value from header
            string authenticationToken = Convert.ToString(
              actionContext.Request.Headers.GetValues("authenticationToken").FirstOrDefault());
            //authenticationTokenPersistant
            // it is saved in some data store
            // i will compare the authenticationToken sent by client with
            // authenticationToken persist in database against specific user, and act accordingly
            if (authenticationTokenPersistant != authenticationToken)
            {
                HttpContext.Current.Response.AddHeader("authenticationToken", authenticationToken);
                HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
                return;
            }

            HttpContext.Current.Response.AddHeader("authenticationToken", authenticationToken);
            HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
            return;
        }
        actionContext.Response = 
          actionContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
        actionContext.Response.ReasonPhrase = "Please provide valid inputs";
    }
}

Custom Handle Exception attribute:

To implement custom Handle Exception attribute you need to extend "ExceptionFilterAttribute", and override "OnException" method.

You can find the example below:

public class HandleExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Exception != null)
        {
            var exception = actionExecutedContext.Exception;
            var response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.InternalServerError;
            response.ReasonPhrase = exception.Message;
            actionExecutedContext.Result = response;
        }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here