簡體   English   中英

限制對MVC操作的訪問

[英]Restricting Access to MVC Actions

我有一個ASP.NET MVC網站,在該網站上已經建立了權限系統。 例如,當當前用戶沒有足夠的權限時,某些鏈接將被隱藏。 但是,如果他們手動輸入該鏈接的URL,他們仍然可以訪問內容。

我知道我可以使用[Authorize]屬性來阻止沒有正確用戶角色的用戶,但是如何實現自己的屬性來阻止不符合自定義要求的用戶的操作,而不必在每個用戶中都進行手動檢查這些動作?

您可以編寫一個自定義Authorize屬性,並覆蓋AuthorizeCore方法,您可以在其中放置自定義授權邏輯:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authroized = base.AuthorizeCore(httpContext);
        if (!authroized)
        {
            return false;
        }

        // at this stage the base authorization process has passed.
        // now implement your custom authorization logic and return true or false

        // here you have access to the HttpContext and as a consequence to all
        // request and route parameters so you could implement any 
        // authorization logic you want

        // And of course if you want a completely custom authorization logic 
        // ignoring the base functionality don't call the base method above
        // but completely override anything here
    }
}

現在剩下的就是用這個自定義屬性裝飾相應的控制器/動作。

如果使用的是ASP.NET成員資格,則可以配置RoleProvider並為用戶提供角色。

然后,可以使用AuthorizeAttribute上的Roles屬性檢查角色。

[Authorize(Roles="Admin, SuperUser")]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM