ASP.Net MVC 3允许匿名白名单无效

时间:2012-08-06 23:38:01

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

我从一位同事那里接过了一个MVC 3 Razorview项目。我创建了一个忘记密码页面,但是当点击登录页面上忘记密码链接时,网站会要求用户登录。我做了一些谷歌搜索并使用{{1}实现了white listing actions的解决方案}属性。但是,这并没有解决问题。

单步执行代码,永远不会调用忘记密码操作。它被直接推送到帐户控制器上的LogOn操作。 [AllowAnonymous]具有以下代码,即使忘记密码布局不使用它并且在代码中设置了布局,也会调用该代码。

_ViewStart.cshtml

2 个答案:

答案 0 :(得分:5)

您必须在白名单中使用[AllowAnonymous]中包含的视图中使用的控制器的所有操作方法。我在RecoverPassword页面遇到了同样的问题,我意识到我的布局调用了一个不在白名单中的菜单方法。

答案 1 :(得分:2)

你可以试试这个。 http://blog.tomasjansson.com/2011/08/securing-your-asp-net-mvc-3-application/

<强>更新

以下代码正常。它在基类本身中实现了OnAuthorization。

public class MyBaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        var skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                            filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(
                                typeof(AllowAnonymousAttribute), true);
        if (!skipAuthorization)
        {
            base.OnAuthorization(filterContext);
            if (!User.Identity.IsAuthenticated)//Implement your own logic here
            {
                var url = new UrlHelper(filterContext.RequestContext);
                var logonUrl = url.Action("LogOn", "Home", new { reason = "NotAuthorized" });
                filterContext.Result = new RedirectResult(logonUrl);

            }
        }

    }
}

public class HomeController : MyBaseController 
{

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

    [AllowAnonymous]
    public ActionResult PasswordReset()
    {
        return Content("reset your password");
    }

    [AllowAnonymous]
    public ActionResult LogOn(string reason)
    {
        return Content("please log in");
    }
}

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class AllowAnonymousAttribute : Attribute
{
}