2013-03-27 80 views
1

我需要授權用戶禁止在我的MVC 3項目中使用資源。採取以下方法是否是一種好的做法?授權用戶使用資源mvc3

interface IResource 
{ 
    string Id { get; set; } 
    bool Authorize(User user); 
} 

class User 
{ 
    // some logic for user 
} 

class ResourceA : IResource 
{ 
    public string Id { get; set; } 

    public ResourceA(string id) 
    { 
     Id = id; 
    } 

    bool Authorize(User user) 
    { 
     // Query database to check if user has permission to the resource 
     // return true if the user has, otherwise false 
    } 
} 

class TestController : Controller 
{ 
    // Get details of resource A 
    public ActionResult Get(User user, string resourceId) 
    { 
     IResource resource = new ResourceA(resourceId); 
     if (resource.Authorize(user)) 
     { 
      // do stuff 
     } 
     else 
     { 
      throw HttpException(403, "No permission"); 
     } 
    } 
} 

在上面的實施:

網站的所有資源都被迫實施的IResource接口。

與資源交互的所有請求都需要實現授權代碼。

任何幫助將不勝感激。

+0

有許多好方法可以做到,過濾器和屬性。授權屬性例如檢查msdn。 – 2013-03-27 06:21:42

+0

檢查授權屬性和自定義操作過濾器。 – ssilas777 2013-03-27 06:39:11

回答

0

解決方案看起來不錯。如果您具有與資源相關的特定控制器和操作,則還可以使用ActionFilter,您可以在其中創建自定義邏輯,並在驗證失敗時檢查並重定向。屬性也是中央邏輯系統的一種方式。解決方案取決於你的用戶將如何與資源進行交互。