2011-11-28 119 views
1

我知道這已經在這裏得到解答,但是即使在遵循我所能找到的所有解決方案之後,我仍然無法讓我的角色在我的系統中工作。沒有提供商的Asp.Net MVC身份驗證角色

我有一個Asp.Net MVC應用程序,基於窗體的身份驗證。它不使用本地數據庫,而是使用OpenAuth/OpenID進行身份驗證,並使用數據庫查找表來查找應用程序角色。

按照主的建議,我實現了角色在Global.asax,如:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    //Fires upon attempting to authenticate the use 
    if (HttpContext.Current.User != null && 
     HttpContext.Current.User.Identity.IsAuthenticated && 
     HttpContext.Current.User.Identity.GetType() == typeof (FormsIdentity)) 
     Thread.CurrentPrincipal = HttpContext.Current.User = OpenAuthPrincipal.Get(HttpContext.Current.User.Identity.Name); 
} 

這裏OpenAuthPrincipal.Get是一個非常簡單的靜態方法包裝與角色openauth ID:

public static IPrincipal Get(string userId) 
{ 
    var db = new WebData(); 
    var user = db.Users.Find(userId); 

    return new GenericPrincipal(new Identity(user), user.Roles.Split('|')); 
} 

然而,當我達到如下功能:

[Authorize(Roles = "Admin")] 
public ActionResult Edit(int id) 
{ 
     ... 
} 

它失敗。如果我刪除角色限制,並在調試器中檢查User.IsInRole("Admin"),我會得到一個false。但是,如果我在Global.asax中進行檢查,我會得到true

我知道User.Identity.Name是正確的。而且IIdentity也沒有被修改。然而只有角色丟失了。

這個問題的原因是什麼?

更新:

下面推薦的解決方案並沒有直接工作,而這一改變固定的問題,對我來說:

protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) 
{ 
    httpContext.User = OpenAuthPrincipal.Get(httpContext.User.Identity.Name); 

    return base.AuthorizeCore(httpContext); 
} 

回答

2

按照主的建議,我實現了在全球的角色.asax像:

不知道你從哪裏得到這個主要建議,但在ASP.NET中MVC通常使用授權操作過濾器。而且,由於默認授權過濾器不會做你需要什麼,你寫你自己:

public class OpenIdAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var authorized = base.AuthorizeCore(httpContext); 
     if (authorized) 
     { 
      httpContext.User = OpenAuthPrincipal.Get(httpContext.User.Identity.Name); 
     } 
     return authorized; 
    } 
} 

然後:

[OpenIdAuthorize(Roles = "Admin")] 
public ActionResult Edit(int id) 
{ 
    ... 
} 
+0

好吧,我會考慮這一點。當我搜索這個問題時,我在StackOverflow中看到了這個解決方案,並且在網絡中也有類似的代碼。無論如何,顯然它不工作。 – sukru

+0

謝謝,我得到了它的工作。但是,這似乎是基於方法的。是否可以覆蓋整個網站? – sukru

+0

你也可以用你的屬性裝飾整個控制器。 –