@manhng

Welcome to my blog!

Authorize Attribute in ASP.NET MVC

November 4, 2019 10:12

Authorize Attribute in ASP.NET MVC (edit)

Helper:

        public class ApplicationAuthorizeAttribute : AuthorizeAttribute
	{
		protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
		{
			var httpContext = filterContext.HttpContext;
			var request = httpContext.Request;
			var response = httpContext.Response;
			var user = httpContext.User;

			if (request.IsAjaxRequest())
			{
				if (user.Identity.IsAuthenticated == false)
					response.StatusCode = (int)HttpStatusCode.Unauthorized;
				else
					response.StatusCode = (int)HttpStatusCode.Forbidden;

				response.SuppressFormsAuthenticationRedirect = true;
				response.End();
			}

			base.HandleUnauthorizedRequest(filterContext);
		}
	}

Controller:

		[HttpPost]
		public ActionResult GetData1()
		{
                    return Json(new
                    {
                        Items = new[] { "String 1", "String 2", "String 3" }
                    });
                }

		[HttpPost]
		[ApplicationAuthorize]
		public ActionResult GetData2()
		{
			return Json(new
			{
				Items = new[] { "String 1", "String 2", "String 3" }
			});
		}

		[HttpPost]
		[ApplicationAuthorize(Roles = "admin")]
		public ActionResult GetData3()
		{
                    return Json(new
                    {
                        Items = new[] { "String 1", "String 2", "String 3" }
                    });
                }

Categories