繁体   English   中英

ASP.Net MVC 3允许匿名白名单不起作用

[英]ASP.Net MVC 3 Allow Anonymous white list not working

我从一位同事那里接管了MVC 3 Razorview项目。 我创建了一个忘记密码的页面,但是当单击“登录”页面上的忘记密码的链接时,网站要求用户登录。我进行了一些谷歌搜索,并使用[AllowAnonymous]属性实现了白名单操作的解决方案。 但是,这不能解决问题。

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

@{
    Layout = Request.IsAuthenticated ? "~/Views/Shared/_Layout.cshtml" : null;
}

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

你可以试试看 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
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM