1

I have a WCF service binding with netTcp with over 100 methods, I would like to secure all the methods based on a Windows User Group.

I know you can put the attribute [PrincipalPermission(SecurityAction.Demand, Role = "MyWindowsUserGroup")] before each method.

Do I need to do this individually for every single method or is there a way to have every method in the service secured with this same user group by default?

Dominic Zukiewicz
  • 8,258
  • 8
  • 43
  • 61
dave
  • 43
  • 6

1 Answers1

1

You can add PrincipalPermission at class level as well as method.

// Before:
public class AdministrationService : IAdminService
{
   [PrincipalPermission(SecurityAction.Demand, Role = "Domain\Admin Service Admins")]
   public bool DisableAdministrator(int userId)
   {
   }

   [PrincipalPermission(SecurityAction.Demand, Role = "Admin Service Admins")]
   public bool DeleteAdministrator(int userId)
   {
   }
}

// After:

[PrincipalPermission(SecurityAction.Demand, Role = "Admin Service Admins")]
public class AdministrationService : IAdminService
{
   public bool DisableAdministrator(int userId)
   {
   }

   public bool DeleteAdministrator(int userId)
   {
   }
}

You can also define multiple instances of it, if you wish to have multiple types of permissions.

[PrincipalPermission(SecurityAction.Demand, Role = "Admin Service Admins")]
[PrincipalPermission(SecurityAction.Demand, Role = "Domain\Domain Admins")]
[PrincipalPermission(SecurityAction.Demand, Role = "Domain\Power Users")]
public class AdministrationService : IAdminService
{
   public bool DisableAdministrator(int userId)
   {
   }

   public bool DeleteAdministrator(int userId)
   {
   }
}
Dominic Zukiewicz
  • 8,258
  • 8
  • 43
  • 61
  • 1
    Hi Dominic,Thanks, that looks spot on. – dave Jul 13 '15 at 08:54
  • I don't know if this never worked, or if WCF has changed since 2015, but the PrincipalPermissionAttribute can be added only at the method level. This is per my own observation and [How to: Restrict Access with the PrincipalPermissionAttribute Class](https://learn.microsoft.com/en-us/dotnet/framework/wcf/how-to-restrict-access-with-the-principalpermissionattribute-class): "If you apply the PrincipalPermissionAttribute attribute to a contract a SecurityException will be thrown. You can only apply the attribute at the method level." – Pat May 22 '20 at 04:13
  • @Pat: If you apply it to the interface (contract), that might be the case. The example above was applying it to the concrete class. Also, I checked the Definition on MS Docs and it is valid to apply it to classes, via the AttributeUsage.Class assignment. (https://learn.microsoft.com/en-us/dotnet/api/system.security.permissions.principalpermissionattribute?view=dotnet-plat-ext-3.1#definition) – Dominic Zukiewicz May 23 '20 at 06:40