4

我需要用我的mvcSiteMapProvider V4軟件來實現角色安全。我正在使用它與MVC3。如何用mvcSiteMapProvider實現安全性?

例mvcSiteMap代碼:

 <mvcSiteMapNode roles="Admin" title="Your Subscription (All Users)" controller="SOU" action="ListSubscribers"> 

該角色屬性值沒有影響:

 <mvcSiteMapNode roles="NoAdmin" title="Your Subscription (All Users)" controller="SOU" action="ListSubscribers"> 

這是相同的。如果管理員登錄,我希望上述不起作用?我希望第一個例子在只有用戶登錄時才能工作。

...但是沒有效果。

非常感謝

回答

10

默認情況下,安全調整功能未啓用。你需要做的第一件事是打開它。

內部DI(web.config中):

<add key="MvcSiteMapProvider_SecurityTrimmingEnabled" value="true"/> 

外部DI(在MvcSiteMapProvider模塊):

bool securityTrimmingEnabled = true; // First line in the module 

那麼你應該把MVC [授權]屬性上每個動作方法你想要保護。在MVC4 +中,您還可以將其放在控制器級別或全局註冊,然後使用[AllowAnonymous]屬性選擇性地允許未經身份驗證的用戶允許操作方法。

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new AuthorizeAttribute()); 
    } 
} 

[Authorize(Roles="Admin,Manager")] 
public class MyController 
{ 
    // Everyone has access 
    [AllowAnonymous] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    // Only Admin and Manager roles have access, everyone else is denied 
    public ActionResult About() 
    { 
     return View(); 
    } 
} 

XML中的roles屬性是爲了與ASP.NET向後兼容。對於MVC,唯一真正的安全性是使用[Authorize]屬性(或通過爲自己的方案繼承它),因爲它是保證資源無法通過替代路線訪問的唯一方法。

+0

非常感謝 – SamJolly

+0

我發現網站地圖中的Roles屬性對於鏈接外部資源的菜單很有用。它似乎完美與表單身份驗證。 –

+0

@MattiasÅslund - 我改正了我的帖子。角色屬性適用於Forms身份驗證,因爲它是爲ASP.NET設計的。但是,ASP。NET安全性基於文件系統和/或對於MVC來說不夠好的URL(一個資源可以鏈接到多個URL,並且不一定涉及文件系統),所以您應該只使用roles屬性與ASP.NET的互操作性。 – NightOwl888

1

在SOUController,你有沒有[授權]屬性的地方添加? MvcSiteMapProvider使用它來確定ACL。

0

如果您使用站點地圖,您可以/必須(以上方法對我無效)指定站點地圖中的角色。

<mvcSiteMapNode title="Rechnungen" controller="Customer/Bills" action="Index" roles="CompanyAdmin"/> 
+0

我不確定您從哪裏獲得控制器=「客戶/賬單」語法,但不支持。如果這實際上是你想要做的,使用area =「Customer」controller =「Bills」。 – NightOwl888

+0

我既不是,但事情應該起作用的角色。 – Remy

0

我只是把

<add key="MvcSiteMapProvider_SecurityTrimmingEnabled" value="true"/> 

在Web.config中的的appSettings,就像這樣:

<appSettings> 
    <add key="webpages:Version" value="2.0.0.0" /> 
    <add key="webpages:Enabled" value="false" /> 
    <add key="PreserveLoginUrl" value="true" /> 
    <add key="ClientValidationEnabled" value="true" /> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
    <add key="jqueryTheme" value="redmond" /> 
    <add key="MvcSiteMapProvider_IncludeAssembliesForScan" value="Cost3" /> 
    <add key="MvcSiteMapProvider_UseExternalDIContainer" value="false" /> 
    <add key="MvcSiteMapProvider_ScanAssembliesForSiteMapNodes" value="true" /> 

    <add key="MvcSiteMapProvider_SecurityTrimmingEnabled" value="true"/> 

    </appSettings> 

,並把[授權]屬性上的每個控制器或動作,像這樣的:

[Authorize(Roles = "Administrator")] 
public class UserManagementController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 
} 

然後OK!