How to create a custom JsonAuthorize attribute to protect actions that return JsonResults?

I was thinking about how to properly protect the JsonResult action with a custom attribute instead of doing it with every action, for example here ASP.NET MVC JsonResult and AuthorizeAttribute

if (!User.Identity.IsAuthenticated)
    return Json("Need to login");

But the question is how can I create an attribute that returns Json. So I started with this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class JsonAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            IPrincipal user = httpContext.User;

            if (!user.Identity.IsAuthenticated)
            { 
               //? 
            }

            //Need to return json somehow ?
        }
    }

How can I return a json result from such an attribute? any ideas?

+1
source share
2 answers

You can use ActionFilterAttributeone that allows you to return a result without using httpcontext.response.writeor everything.

public class JsonActionFilterAttribute : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (!HttpContext.Current.User.Identity.IsAuthenticated) {
            filterContext.Result = new JsonResult() { Data = "Need to login." };
        }
        base.OnActionExecuting(filterContext);
    }
}
+3
source

1 way - override AuthorizeAttribute.HandleUnauthorizedRequest

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    throw new CustomUnauthorizedException();
}

... Global.asax:

protected void Application_Error(object sender, EventArgs e)
{
    Exception error = Server.GetLastError();
    if (error is CustomUnauthorizedException) {
        if (AjaxRequest(Request)) {
            ... return Json response.
        } else {
            ... redirect
        }
    }
}

, , Global.asax

+3

Source: https://habr.com/ru/post/1788412/


All Articles