gpt4 book ai didi

c# - 身份验证/PrincipalPermission 不起作用

转载 作者:行者123 更新时间:2023-11-30 12:16:34 25 4
gpt4 key购买 nike

我在 WCF 工作,正在编写基于 IHttpModule 的身份验证管理器,它运行良好。我的 Authentication 类中的一个方法在 Context.User 中创建了一个 GenericPrincipal 对象。

例如

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

Service 中的一种方法中,我想分配给用户 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();
}

最佳答案

对于 WCF,您需要通过 very specific mechanism 关联自定义主体,效果很好。另请注意,属性通常不会导致代码执行,并且只有在通过反射显式完成时才会被调用(除非您使用的是 PostSharp)。您不能只添加一个属性并让它自动执行操作。 MVC 等给人印象,但 MVC 中有代码检查属性并手动执行它们。

关于c# - 身份验证/PrincipalPermission 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5135770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com