2011-02-27 132 views
4

您好我在WCF工作,我寫我的基於IHttpModule我的身份驗證管理器,它工作正常。我的Authentication類中的一種方法在Context.User中創建GenericPrincipal對象。身份驗證/ PrincipalPermission不工作

例如

app.Context.User = new GenericPrincipal(new GenericIdentity("Scott"), new string[] { "read" }); 

在在服務方法之一,我想用戶PrincipalPermissionAttribute和我這樣做不是如何工作的,但它總是拋出SecurityException異常。示例:

[WebGet(UriTemplate = "/", RequestFormat=WebMessageFormat.Xml, ResponseFormat=WebMessageFormat.Xml)] 
    [PrincipalPermission(SecurityAction.Demand, Role="read")] // it throw SecurityException 
    public SampleItem GetCollection() 
    { 
     bool user = HttpContext.Current.User.IsInRole("read"); // return true 
     bool user1 = HttpContext.Current.User.IsInRole("write"); // return false 

     return SampleItem.GetSampleItem(); 
    } 

也許PrincipalPremissionAttribute不使用Context.Current.User?但如果不是那麼什麼? :>

我嘗試刪除麻煩,我可以把我的非常簡單的屬性

[AttributeUsage(AttributeTargets.Method, AllowMultiple=true, Inherited=false)] 
public class MyAuthorizationAttribute : Attribute 
{ 
    public MyAuthorizationAttribute(params string[] roles) 
    { 
     foreach (string item in roles) 
     { 
      if(HttpContext.Current.User.IsInRole(item) == false) 
      { 
       HttpContext.Current.Response.Clear(); 

       HttpContext.Current.Response.StatusCode = 401; 

       HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Basic Realm"); 
       HttpContext.Current.Response.StatusDescription = "Access Denied"; 
       HttpContext.Current.Response.Write("401 Access Denied"); 

       HttpContext.Current.Response.End(); 
      } 
     } 
    } 
} 

但是,應用程序無法使用此功能。意思是當我在MyAttribute構造函數上設置斷點時,編譯器不會停留在這個關鍵點上,它不會看到這一點。

[WebGet(UriTemplate = "/", RequestFormat=WebMessageFormat.Xml, ResponseFormat=WebMessageFormat.Xml)] 
    [MyAuthorization("read")] 
    public SampleItem GetCollection() 
    { 
     bool user = HttpContext.Current.User.IsInRole("read"); // return true 
     bool user1 = HttpContext.Current.User.IsInRole("write"); // return false 

     return SampleItem.GetSampleItem(); 
    } 
+0

您是否使用AspNetCompatibility? – 2011-02-27 21:36:04

+0

是的,我使用AspNetCompatibility。它的標準寫在web.config becouse我使用WCF REST 40模板 – user634199 2011-02-27 22:05:30

回答

3

有了WCF,你需要自定義的校長通過very specific mechanism,工作正常關聯。還請注意,屬性一般不要導致代碼執行,並且只有在通過反射(除非您使用PostSharp)明確完成後纔會調用。你不能只添加一個屬性並讓它自動執行。 MVC等給印象,但有MVC中的代碼檢查屬性並手動執行它們。

+0

謝謝你的答案:) – user634199 2011-02-27 21:26:09