2013-03-12 161 views
1

我的任務是爲我們的MVC 4.0項目創建一個自定義成員資源提供程序。自定義成員資格提供程序+自定義CodeAccessSecurityAttribute

根據一個屬性([Authorize]?),它必須知道允許嘗試的用戶是否允許使用該方法。

目前我有這樣的:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 
public class TestAuthorize : CodeAccessSecurityAttribute 
{ 
    public TestAuthorize(SecurityAction action) 
     : base(action) 
    { 
    } 

    public override IPermission CreatePermission() 
    { 
     throw new NotImplementedException(); 
    } 
} 

當我添加 return new PrincipalPermission(null,null,true)我期待許可的情況下有效,並且用戶可以訪問方法。

當我添加 return new PrincipalPermission(null.null,false)我期望的權限是無效的,用戶將被拒絕訪問該方法。

但是,只有當我使用throw new SecurityException("You are denied access")時,它纔會停止,這也會強制MVC應用程序停止,除非在客戶端處理此異常(使用try catch)。

我們有可能在我們的MVC項目中處理這個異常嗎?

爲我們所希望的例子已經通過使用屬性來完成:

[TestAuthorize(SecurityAction.Demand)] 
public List<string> GetList() 
{ 
    //if access, return new List(); 
    //if no access, return null; 
} 

回答

1

敢肯定你希望從AuthorizeAttribute繼承這裏,不CodeAccessSecurityAttribute。在屬性中,您覆蓋AuthorizeCore,如果允許用戶繼續,則只需返回true;如果他們未被授權執行該方法的任何操作,則返回false。一個false結果將觸發一個HTTP-401 Unauthorised響應,ASP.NET將通過將用戶重定向到登錄頁面自動處理,以便他們可以作爲具有正確訪問權限的用戶登錄,但如果願意,您可以更改此行爲。

事實上,你甚至可能不需要創建自己的屬性;如果您使用的是現有的ASP.NET MVC記憶體提供程序,或者您可以使用任何方法來使用它,那麼現有的AuthorizeAttribute將適用於您。

+1

我試過這個; Nomather它返回true的真假..它仍然讓人們訪問該方法。 – 2013-03-13 08:06:42

+0

在另一個問題中,我被告知授權屬性不是我想要的,因爲我提供的是web服務而不是網站。當給定的方法/控制器/對象有一個httpcontext時,Authorize屬性才起作用 – 2013-03-13 15:25:41

相關問題