How do I list the requesting user's roles in a WCF service?
-
22-08-2019 - |
Question
Just started getting to grips with WCF security. How do I list a user's roles at the service?
E.g.
// Could use declarative security here, i.e. using PrincipalPermission attribute
public string MyService()
{
// Would like some code that does something like:
foreach( Role role in CurrentUser.Roles )
{
}
}
Thanks
Solution
When dealing with Windows groups you can use this code:
foreach (IdentityReference idRef in WindowsIdentity.GetCurrent().Groups)
{
Console.WriteLine(idRef.Translate(typeof(NTAccount)).Value);
}
OTHER TIPS
The role-based security infrastructure in .NET (ie IPrincipal) doesn't allow fetching all of a user's roles. You can only inquire whether a user is in a specific role (via IPrincipal.IsInRole("role-name")).
However, there are solutions if you don't mind being tied to a particular authentication/authorization setup. For example, another poster pointed out how to get the user's roles when using Windows authentication.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow