您好我在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();
}
您是否使用AspNetCompatibility? – 2011-02-27 21:36:04
是的,我使用AspNetCompatibility。它的標準寫在web.config becouse我使用WCF REST 40模板 – user634199 2011-02-27 22:05:30