Home > Enterprise >  ASP.NET MVC AllowAnonymous attribute not working
ASP.NET MVC AllowAnonymous attribute not working

Time:03-15

AllowAnonymous attribute is not working at all in my MVC project (target framework 4.7).

I have tried everything on the internet but still, I am always redirected to the login page. Even I have tried: mvc-override-allowanonymous-attribute

What is actually I am missing?

This is my controller:

using OnDemand.Helper;
using System.Web.Mvc;

namespace OnDemand.Controllers
{
    [App_Auth.AllowAnonymous]
    [System.Web.Mvc.AllowAnonymous]
    public class AdminDashboardController : Controller
    {
        private readonly DashboardHelper _dashboardHelper;
        public AdminDashboardController()
        {
            _dashboardHelper = new DashboardHelper();
        }
        [App_Auth.AllowAnonymous] // Not Working
        [System.Web.Mvc.AllowAnonymous] // Not Working
        public ActionResult Index()
        {
            return View(_dashboardHelper.DashboardData());
        }
    }
}

Filter configuration:

using System.Web.Mvc;
using OnDemand.App_Auth;

namespace OnDemand.App_Start
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new SessionExpireAttribute()); //check session expire and redirect to login
        }
    }
}

Global asax class:

using OnDemand.App_Start;
using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace OnDemand
{
    public class MvcApplication : HttpApplication
    {
        protected void Application_BeginRequest()
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            Response.Cache.SetNoStore();
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        protected void Session_Start()
        {
            Session.Timeout = 24 * 60; // return 24 hours
        }
    }
}

Custom Authorize and AllowAnonymous attribute classes:

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

namespace OnDemand.App_Auth
{
    public class AuthorizeAccessAttribute : AuthorizeAttribute
    {

        private readonly int code;
        public AuthorizeAccessAttribute(int code)
        {
            this.code = code;
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var hasAccess = false;

            if (httpContext.Session["Roles"] == null) return false;

            if (SectionsAndFeatures.HasAccess(code, httpContext.Session["Roles"] != null ? httpContext.Session["Roles"].ToString() : string.Empty))
            {
                hasAccess = true;
            }
            return hasAccess;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectToRouteResult(
                                   new RouteValueDictionary
                                   {
                                       { "action", "UnauthorizedAccess" },
                                       { "controller", "Home" },
                                       { "area", "" }
                                   });  //new HttpUnauthorizedResult("You are not authorized.");
        }
    }

    public class AllowAnonymousAttribute : AuthorizeAttribute
    {
        public AllowAnonymousAttribute()
        {

        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool IsAuthenticAttribute =
                (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) &&
                filterContext.HttpContext.User.Identity.IsAuthenticated;

            if (!IsAuthenticAttribute)
            {
                base.OnAuthorization(filterContext);
            }
        }
    }
}

Web configuration:

<location path="AdminDashboard/Index">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
</location>

CodePudding user response:

Why not just use it in the standard way? simple AllowAnonymous attribute without duplication or custom attributes.

[AllowAnonymous]
public class AccountController : Controller
{
    [AllowAnonymous]
    public ActionResult Login()
    {
    }

    public ActionResult Logout()
    {
    }
}

Or in your code:

using OnDemand.Helper;
using System.Web.Mvc;

namespace OnDemand.Controllers
{
    [AllowAnonymous]
    public class AdminDashboardController : Controller
    {
        private readonly DashboardHelper _dashboardHelper;
        public AdminDashboardController()
        {
            _dashboardHelper = new DashboardHelper();
        }
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View(_dashboardHelper.DashboardData());
        }
    }
}

CodePudding user response:

I found that we are using a custom method, I just needed to include my controller name in that list:

public static List<string> ByPassController()
        {
            try
            {
                return new List<string>
                {
                    "Access",
                    "InterpreterSelection",
                    "Language",
                    "Log",
                    "CallBack",
                    "Controller",
                    "IvrOnDemand",
                    "Main",
                    "CallDetail",
                    "ConferenceParticipant",
                    "DashBoardData",
                    "CallWaitingResponse",
                    "IVRRejoinParticipant",
                    "IVRAuto",
                    "OnDemand",
                    "Assignment",
                    "SilentListenCallback",
                    "AutoOnDemand",
                    "StelCallLogs",
                    "DialOut",
                    "AdminDashboard",
                    "Developer"
                };
            }
            catch (Exception ex)
            {
                LogWriter.ErrorLogWriter(nameof(CommonFunction), nameof(ByPassController), ex.Message);
                return new List<string>();
            }
        }
  • Related