Introduction
This code allows a specif user from active directory to perform a specific task i.e viewing important employee information (companies can't allow every employee to have access to that kind of information)
Using the code
using System.ServiceModel;
using System.DirectoryServices.AccountManagement;
Firstly I have my web.config which looks like this (I won't post the whole file):
<system.web>
<authentication mode="Windows" />
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="RemoteOnly" />
<trust level="Full" />
<identity impersonate="false" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" >
<extendedProtectionPolicy policyEnforcement="Always" />
</transport>
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
I have two functions, and each function can be processed by a certain group of people from the AD groups. This is what I did on my functions on the service implementation:
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
Public MyFunction()
{
string whoAmI = ServiceSecurityContext.Current.PrimaryIdentity.Name;
PrincipalContext context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "APP_EMPLOYEEWS_BIO");
UserPrincipal user = UserPrincipal.FindByIdentity(context,whoAmI)
if(!user.IsMemberOf(group))
{
throw new SecurityException("Access Denied: User has no permission to process the request");
}
else
{
}
I hope someone will find this helpful and not struggle as i did.