Authorize attribute and jquery AJAX in asp.net MVC

Working example: https://github.com/ronnieoverby/mvc-ajax-auth Important parts: AjaxAuthorizeAttribute: using System.Web.Mvc; namespace MvcApplication1 { public class AjaxAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext context) { if (context.HttpContext.Request.IsAjaxRequest()) { var urlHelper = new UrlHelper(context.RequestContext); context.HttpContext.Response.StatusCode = 403; context.Result = new JsonResult { Data = new { Error = “NotAuthorized”, LogOnUrl = urlHelper.Action(“LogOn”, “Account”) }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; … Read more

Override Authorize Attribute in ASP.NET MVC

Edit: Since ASP.NET MVC 4 the best approach is simply to use the built-in AllowAnonymous attribute. The answer below refers to earlier versions of ASP.NET MVC You could create a custom authorisation attribute inheriting from the standard AuthorizeAttribute with an optional bool parameter to specify whether authorisation is required or not. public class OptionalAuthorizeAttribute : … Read more