Authentication / PrincipalPermission not working

Hi, I work in WCF and I am writing my Authentication Manager, which based on IHttpModule is working fine. One of the methods of my authentication class creates a GenericPrincipal object in Context.User.

for instance

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

In one of the methods in the service, I want the PrincipalPermissionAttribute user and I do not work, but he always throws a SecurityException. Example:

  [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(); } 

Perhaps PrincipalPremissionAttribute is not using Context.Current.User? but if not, then what ?:>

I am trying to remove this problem and I am making a very simple attribute

 [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(); } } } } 

But the application cannot use this. It is average, when I set a breakpoint on the MyAttribute constructor, the compiler does not stop at this breakpoint, it does not see it.

  [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(); } 
+4
source share
1 answer

With WCF, you need to associate custom principles with a very specific mechanism that works just fine. Also note that attributes, usually not , cause code to execute and are called only when explicitly processed via reflection (if you are not using PostSharp). You cannot just add an attribute and do it automatically. MVC etc. It gives the impression, but in MVC there is code for checking attributes and executing them manually.

+3
source

Source: https://habr.com/ru/post/1341549/


All Articles