2011-02-27 134 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