MVC 4 override AuthorizeAttribute not working

user2130167 picture user2130167 · Mar 4, 2013 · Viewed 13.6k times · Source

I created a basic MVC 4 project. Added the HomeController and Home\Index.cshtml and ContactUs.cshtml. Add route in Global.asax for ContactUs.

Add a Folder Auth and add a class Auth.css in Auth folder.

using System;
using System.Web;
using System.Web.Http;
using System.Net.Http;


namespace MvcApplicationTestProject1
{
    public class AuthAttribute : AuthorizeAttribute
    {
        //public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        //{
        //    HandleUnauthorizedRequest(actionContext);
        //}        

        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Redirect);
            response.Headers.Add("Location", "http://www.google.com");
            actionContext.Response = response;
        }
        //MVC 4 Web.Http.AuthorizeAttribute has IsAuthorized function but not AuthorizeCore
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            return false;
        }
    }
}

In HomeController

public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Home/  
        [Auth]       
        public ActionResult ContactUs()
        {
            return View();
        }
    }

The problem is when run the code and visit http://localhost:[port number here]/Home/ContactUs, it does not hit on the override class AuthAttribute.

Does the code have something wrong?

Answer

MikeSmithDev picture MikeSmithDev · Mar 4, 2013

Your comment says you are trying to achieve what is in this post, and yet you copied code not from that post at all, but from a previous SO post: Using custom authorization in MVC 4 that was referring to Web API. And in reading that post you see the difference is in what AuthorizeAttribute you use. You are using System.Web.Http instead of System.Web.Mvc.

If you used the code that you referred to in your comment, then you'd find it would work:

using System.Web;
using System.Web.Mvc;

namespace MvcApplicationTestProject1
{
    public class AuthAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return false;
        }
    }
}