Custom Authorize Attribute and HTTP 403

In this post, I want to outline in how to create your own Authorize tag and to make sure when you call JSON method with your custom authorize attribute to throw HTTP403 – Forbidden

1. You need to create your own Attribute inherits from AuthorizeAttribute

2. AuthorizeCore is the logic that defines whether you are authorized or not

3. OnAuthorization defines the behaviour when you are not authorized. In this case we want to throw HTTP 403 – forbidden. By doing this in your Javascript, you can catch this 403 error and throw friendly error message to the user

Code Snippet
  1. public class CustomAuthorizeAttribute : AuthorizeAttribute
  2.     {
  3.         protected override bool AuthorizeCore(HttpContextBase httpContext)
  4.         {
  5.             if (httpContext == null) throw new ArgumentNullException(“httpContext”);
  6.             return (SessionData.Member != null && SessionData.Member.MemberId > 0);
  7.         }
  8.         public override void OnAuthorization(AuthorizationContext filterContext)
  9.         {
  10.             base.OnAuthorization(filterContext);
  11.             if (filterContext.Result == null)
  12.             {
  13.                 return;
  14.             }
  15.             else if (filterContext.Result.GetType() == typeof(HttpUnauthorizedResult)
  16.                 && filterContext.HttpContext.Request.IsAjaxRequest())
  17.             {
  18.                 filterContext.Result = new ContentResult();
  19.                 filterContext.HttpContext.Response.StatusCode = 403;
  20.             }
  21.         }
  22.     }

You don’t need to do anything in your controller to implement HTTP403, it is all derived from the custom attribute, you just need to use the attribute and everything will be taken care of. Sample usage

Code Snippet
  1. [CustomAuthorize]
  2.         public ActionResult SaveJobJSON(int jobid)
  3.         {
  4.             string message = string.Empty;
  5.             bool successful = false;
  6.             JobsSavedService JobsSavedService = new JobsSavedService();
  7.             successful = JobsSavedService.SavedJobForMember(jobid, ref message);
  8.             JobsSavedService = null;
  9.             return Json(new { successful = successful, message = message }, JsonRequestBehavior.AllowGet);
  10.         }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s