Tuesday, July 21, 2015

Authorize attribute and jquery AJAX in asp.net MVC

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
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(context);
            }
        }
    }
}
Javascript:
    $(function () {
        $(document).ajaxError(function (e, xhr) {
            if (xhr.status == 403) {
                var response = $.parseJSON(xhr.responseText);
                window.location = response.LogOnUrl;
            }
        });
    });
Use the attribute in a controller:
    [AjaxAuthorize]
    public ActionResult Secret()
    {
        return PartialView();
    }
Do some ajax:
@Ajax.ActionLink("Get Secret", "Secret", new AjaxOptions { UpdateTargetId = "secretArea", })

<div id="secretArea"></div>

Reference: http://stackoverflow.com/questions/5258721/authorize-attribute-and-jquery-ajax-in-asp-net-mvc

No comments: