簡體   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