允许匿名访问MVC4操作

时间:2013-02-06 18:03:55

标签: asp.net asp.net-mvc-4

我正在尝试允许匿名访问我网站的根目录。如果我向site.com/home提出请求,则允许匿名访问。但是,如果我请求site.com/,我会看到一个登录页面。到目前为止,我已经完成了以下工作:

在web.config中,我为所有用户授权“Home”:

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

在FilterConfig.cs中,我添加了以下AuthorizeAttribute:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new System.Web.Mvc.AuthorizeAttribute());
    }

我的Home Index控制器操作如下所示:

    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }

我的路线如下:

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Zoom",
            url: "zoom/{id}",
            defaults: new { controller = "Zoom", action = "Index" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

这是通过路线完成的吗?我完全错过了什么吗?

2 个答案:

答案 0 :(得分:2)

您必须在属性代码中实现逻辑以对其进行过滤。换句话说,您必须检查并查看方法/类是否使用该属性进行注释,然后跳过授权(如果是)(或根据您的方案进行相应处理)。

以下是一个例子:

    /// <summary>
    /// This class is used to ensure that a user has been authenticated before allowing a given method
    /// to be called.
    /// </summary>
    /// <remarks>
    /// This class extends the <see cref="AuthorizeAttribute"/> class.
    /// </remarks>
    public sealed class LoginAuthorize : AuthorizeAttribute
    {
        /// <summary>
        /// The logger used for logging.
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(typeof(LoginAuthorize));

        /// <summary>
        /// Handles the authentication check to ensure user has been authenticated before allowing a method
        /// to be called.
        /// </summary>
        /// <param name="filterContext">The authorization context object.</param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            DateTime methodEntryTime = DateTime.Now;
            Helper.LogMethodEntry(Logger, MethodBase.GetCurrentMethod(), filterContext);

            try
            {
                // determine if the called method has the AllowAnonymousAttribute, which means we can skip
                // authorization
                bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);

                if (!skipAuthorization)
                {
                    base.OnAuthorization(filterContext);

                    // make sure required session data is still present
                    if (string.IsNullOrWhiteSpace(filterContext.HttpContext.Session[Helper.ROLE_NAME] as string))
                    {
                        HandleUnauthorizedRequest(filterContext);
                    }
                }

                Helper.LogMethodExit(Logger, MethodBase.GetCurrentMethod(), methodEntryTime);
            }
            catch (Exception e)
            {
                Helper.LogException(Logger, MethodBase.GetCurrentMethod(), e);
                throw;
            }
        }

        /// <summary>
        /// Handles unauthorized requests. Redirects user to login page.
        /// </summary>
        /// <param name="filterContext">The authorization context object.</param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            DateTime methodEntryTime = DateTime.Now;
            Helper.LogMethodEntry(Logger, MethodBase.GetCurrentMethod(), filterContext);

            try
            {
                base.HandleUnauthorizedRequest(filterContext);

                // redirect user to login page
                filterContext.Result = new RedirectResult("~/Login");

                Helper.LogMethodExit(Logger, MethodBase.GetCurrentMethod(), methodEntryTime);
            }
            catch (Exception e)
            {
                Helper.LogException(Logger, MethodBase.GetCurrentMethod(), e);
                throw;
            }
        }
    }
}

然后,在Global.asax中,您将添加此LoginAuthorize类,如下所示:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new LoginAuthorize());
    filters.Add(new HandleErrorAttribute());
}

答案 1 :(得分:1)

首先,您不应该使用webforms的Webforms授权方式。首先摆脱它。 其次,通过将Authorize属性添加为全局过滤器,您基本上将Authorize属性应用于所有控制器和操作,这真的是您想要的吗? 装饰动作方法或完整控制器更常见。如果控制器具有authorize属性,您仍然可以通过添加AllowAnonymous属性来允许对操作方法进行匿名访问,就像您已经这样做一样。

使用这种方法应该可以正常工作,路线看起来很好。