2013-02-25 65 views
1

我希望有人能夠把我放在正確的軌道上,一直試圖解決這個問題,現在幾個小時。
我目前正在重新開發一個Web應用程序的過程中,我想使用MVC4屬性來管理對應用程序各個部分的訪問。 我遇到的問題是,身份驗證&權限都由Web應用程序必須連接的中間件應用程序處理。MVC4試圖讓安全模型與我的環境一起工作

我想知道是否即使有這個限制,我可以使用安全屬性&讓Web應用程序知道用戶是Authenticated。

回答

1

是的,您將能夠使用現有的授權屬性。您只需編寫一個自定義的MembershipRole提供程序,它將使用您的現有服務,而不是依賴默認的SQL數據庫。

如果你不想經歷所有這些麻煩,你也可以寫一個自定義授權屬性(來源於AuthorizeAttribute)並在AuthorizeCore方法內調用你的服務來檢查當前用戶是否具有所需的角色。

1

當然。這不僅是可能的,而且很容易。如果您可以將ASP.NET角色視爲「活動」,那麼您不需要派生任何東西;你需要的一切是建立在

這些示例假設securityService是與您的中間件應用通信的服務,並有兩個方法,GetUserGetUserRoles

你的登錄操作方法

[HttpPost] 
public ActionResult Login(LoginModel model, string returnUrl) 
{ 
    if (!ModelState.IsValid) return View(); 

    var user = securityService.GetUser(model.Username, model.Password); 
    if (user == null) 
    { 
     ModelState.AddModelError("", "Username or password are incorrect."); 
     return View(); 
    } 

    FormsAuthentication.SetAuthCookie(user.Username, model.Remember); 
    return Redirect(returnUrl); 
} 

在你的Global.asax.cs

protected void Application_AuthenticateRequest() 
{ 
    if (Request.IsAuthenticated) 
    { 
     string username = User.Identity.Name; 
     string[] roles = securityService.GetUserRoles(username); 
     IIdentity identity = new GenericIdentity(username); 
     Context.User = new GenericPrincipal(identity, roles); 
    } 
} 

就是這樣。 Login處理認證(當用戶登錄時),而Application_AuthenticateRequest處理授權(每個請求)。然後,您繼續使用Authorize(Roles = "XYZ")來修飾您的操作方法,確保「XYZ」匹配從您的GetUserRoles方法返回的內容。