Click here to Skip to main content
Click here to Skip to main content

ASP.NET WEB API Custom Authorize and Exception Handling Attributes

, 27 May 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

aamir sajjad
Software Developer (Senior) -
Pakistan Pakistan
i am working as a senior software developer.
 
aamirposwal.blogspot.com

Comments and Discussions

 
QuestionDealing with only Authentication PinmemberM Nabeel24-Feb-14 4:42 
QuestionWhere is this code placed in the solution? PinmemberR. Ian Lee15-Oct-13 6:10 
AnswerRe: Where is this code placed in the solution? Pinmemberaamir sajjad15-Oct-13 7:02 
QuestionQuestion PinmemberMember 798658410-May-12 6:48 
AnswerRe: Question Pinmemberaamir sajjad13-May-12 3:38 
As i don't see any code. so my solution, according to my understanding of the question will be that you need to perform custom check for example "if(Role==Database.Role)" where Database.Role will be fetch from database, and Role is the input, which is being provided by client application. furthermore, you need to set the uri in response of custom authorization attribute. Don't forget to decorate the actions with your customized authorization attribute.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411022.1 | Last Updated 27 May 2012
Article Copyright 2012 by aamir sajjad
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid