2012-06-27 145 views
4

在我的ASP.NET MVC應用程序,我想弄清楚用戶是否有權訪問特定的控制器,由授權數據註解如下限制重寫OnAuthorization在基本控制器

[Authorize(Roles = "user")] 

我試圖重寫OnAuthorization以檢查: -

  • 如果請求被認證(偉大的工程)
  • 如果用戶被授權訪問所請求的視圖(不工作)

我的用戶角色都存儲在我創建了一個SessionManager對象 - SessionManager.ActiveUser.Roles

下面是我在僞代碼的形式,但如果有人可以幫助我得到這個權利,我真的欣賞它。

public class HomeBaseController : Controller 
{ 
    protected override void OnAuthorization(AuthorizationContext context) 
    { 
     if (context.HttpContext.User.Identity.IsAuthenticated) 
     { 
      // these values combined are our roleName 

      bool isAuthorised = context.HttpContext.User.IsInRole(context.RequestContext.HttpContext.User.Identity.); 


      if (!context.HttpContext.User.IsInRole(---the roles associated with the requested controller action (e.g. user)---)) 
      { 
       var url = new UrlHelper(context.RequestContext); 
       var logonUrl = url.Action("LogOn", "SSO", new { reason = "youAreAuthorisedButNotAllowedToViewThisPage" }); 
       context.Result = new RedirectResult(logonUrl); 

       return; 
      } 
     } 
    } 

回答

10

至於根據ProASP.NET MVC3書,他們不建議重寫它,因爲這種方法使用的OutputCache過濾器安全處理的內容緩存的缺省實現覆蓋OnAuthorization。

如果您正在尋找用於自定義驗證(使用窗體身份驗證)和授權(使用角色提供者邏輯然後下面是我如何確保我的應用程序

編輯:下面的邏輯使用內置的表單認證和角色管理器一旦用戶進行身份驗證和授權用戶身份可以用來檢查這兩個認證(User.Identity.IsAuthenticated)和角色User.IsInRole(「管理員」)

在Web.Config中:

<authentication mode="Forms"> 
    <forms loginUrl="~/Account/LogOn" timeout="15" slidingExpiration="true" enableCrossAppRedirects="false" protection="All" /> 
</authentication> 
<roleManager enabled="true" defaultProvider="MyRolesProvider" cacheRolesInCookie="true" cookieProtection="All"> 
    <providers> 
    <clear /> 
    <add name="MyRolesProvider" type="MyApp.Library.CustomRolesProvider" /> 
    </providers> 
</roleManager> 

對於角色授權根據需要擴展RoleProvider並覆蓋方法。

public class CustomRolesProvider : RoleProvider 
{ 
    public override string[] GetRolesForUser(string username) 
    { 
     // You need to return string of Roles Here which should match your role names which you plan to use. 
     //Some Logic to fetch roles after checking if User is Authenticated...  

     return new string[] { "admin" , "editor" }; 
    } 

    //Rest all of them I have kept not implemented as I did not need them... 


} 

在你的控制器現在你可以使用這個:

[Authorize(Roles="Admin")] 
    public class AdminController : Controller 
    { 
    .... 

    } 

進行身份驗證我已經實現了我的自定義身份驗證檢查,但我仍然使用窗體身份驗證:

//This one calls by Custom Authentication to validate username/password 
public ActionResult LogOn(LogOnViewModel model, string returnUrl) 
{ 
    if(Authenticate("test","test")) 
    { 
    ....... 
    } 
} 

public bool Authenticate(string username, string password) 
{ 
    //Authentication Logic and Set the cookie if correct else false. 
    //..... your logic.... 
    //..... 

    FormsAuthentication.SetAuthCookie(username, false); 
}